I was parsing a datetime string using this: http://developer.android.com/reference/java/text/SimpleDateFormat.html but somehow i was getting runtime error on parsing: https://ideone.com/gpFqwp
Can anyone point me to my mistake here?
static String date = "2015-09-17T08:22:49Z";
public static DateFormat inputDatetimeFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
public static DateFormat displayDateFormat = DateFormat.getDateTimeInstance();
public static void main (String[] args) throws java.lang.Exception
{
System.out.println(displayDateFormat.format(inputDatetimeFormatter.parse(date)));
}
DateFormat inputDatetimeFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
See javadoc for SimpleDateFormat in Java 7
or use
DateFormat inputDatetimeFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
See javadoc for SimpleDateFormat in Java 6
here is a sample
Change inputDatetimeFormatter to new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");. Then it will run fine.
EDIT : What is the purpose of the Z at the end of your date string?
Is it just a letter that you always want to be there?
Then you will have to change inputDatetimeFormatter to the above.
If the purpose of Z is for the time zone then your date string is wrong (shouldn't contain Z but a time zone, e.g. -0800).
Then it would give :
static String date = "2015-09-17T08:22:49-0800"; // Replace -0800 by wanted time zone
public static DateFormat inputDatetimeFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); // Now you can use Z (instead of 'Z') to indicate that the time zone is following
Related
I am getting a date value as 1598331600000 from a API call
I am trying to convert this to Readable format using SimpleDateFormat
But i am getting Out of Range Compile Time Error in the Date Constructor
This is my Program
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Calendar cal = Calendar.getInstance();
Date date = new java.sql.Date(1598331600000);
SimpleDateFormat sdf = new java.text.SimpleDateFormat("MMddyyyy");
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
}
}
Could you please let me know how to resolve this error .
1598331600000 without a suffix is treated as an int, and this value is too big for it (int can hold values up to around 2 billion, 2^31 - 1). Use L suffix for long type, which can hold values up to 2^63 - 1: 1598331600000L.
I would recommend to use java-8 date time api, and stop using legacy Calendar, SimpleDateFormat
Instant.ofEpochMilli(1598331600000l)
.atZone(ZoneId.systemDefault())
.format(DateTimeFormatter.ofPattern("MMddyyyy")) //08252020
Your value here is treated as integer.
Date date = new java.sql.Date(1598331600000);
The constructor can take Long values. Like this :
long millis=System.currentTimeMillis();
Date date = new java.sql.Date(millis);
Hence it is throwing the error.
Try out this code :
import java.util.*;
import java.text.SimpleDateFormat;
public class Main{
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
/*long millis=System.currentTimeMillis(); <---- This also works
Date date = new java.sql.Date(millis);*/
Date date = new java.sql.Date(1598331600000L); // <---Look the L for Long here
SimpleDateFormat sdf = new java.text.SimpleDateFormat("MMddyyyy");
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
}
}
Output :
08252020
// input format: dd/MM/yy
SimpleDateFormat parser = new SimpleDateFormat("dd/MM/yy");
// output format: yyyy-MM-dd
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(formatter.format(parser.parse("12/1/20"))); // 0020-11-01
I am using the above code but it is giving me year as '0020' instead of '2020'.
Use java.time for this:
public static void main(String[] args) {
String dateString = "12/1/20";
LocalDate localDate = LocalDate.parse(dateString, DateTimeFormatter.ofPattern("dd/M/yy"));
System.out.println(localDate.format(DateTimeFormatter.ISO_LOCAL_DATE));
}
The output is
2020-01-12
Pay attention to the amount of M in the patterns, you cannot parse a String that contains a single digit for a month using a double M here.
Most Java devs would be tempted to answer SimpleDateFormat but it's not thread safe.
So I recommend you use Java 8 DateFormat.
Assuming your current Date is a String:
DateFormat dateFormat = new DateFormat("yyyy-MM-dd") ;
String dateString ="20/4/20";
LocalDate date = LocalDate.parse(dateString, dateFormat);
If you are using less than Java 8 use joda time for the same classes.
Once you have converted it as a date object use required format and use LocalDate.
format(date, new DateFormat("yyyy-MM-dd")) ;
I have use case in java where we want get the locale specific date. I am using DateFormat.getDateInstance
final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM,
Locale.forLanguageTag(locale)));
This translates the dates but ja-JP this translates the date "17 January 2019" to "2019/01/17" but I need something like "2019年1月17日". For all other locales this correctly translates the date.
Please let know if there is other method to get this.
This worked for me:
public static void main(String[] args) throws IOException {
final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL, Locale.JAPAN);
Date today = new Date();
System.out.printf("%s%n", dateFormat.format(today));
}
and MEDIUM acted exactly how you said
UPD: or using newer ZonedDataTime as Michael Gantman suggested:
public static void main(String[] args) throws IOException {
ZonedDateTime zoned = ZonedDateTime.now();
DateTimeFormatter pattern = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL).withLocale(Locale.JAPAN);
System.out.println(zoned.format(pattern));
}
Just to mention: SimpleDateFormat is an old way to format dates which BTW is not thread safe. Since Java 8 there are new packages called java.time and java.time.format and you should use those to work with dates. For your purposes you should use class ZonedDateTime Do something like this:
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("..."));
to find out correct zone id for Japan use
ZoneId.getAvailableZoneIds()
Later on to format your Date correctly use class DateTimeFormatter
The trick is to use java.time.format.FormatStyle.LONG:
jshell> java.time.format.DateTimeFormatter.ofLocalizedDate(java.time.format.FormatStyle.LONG).withLocale(java.util.Locale.JAPAN)
$13 ==> Localized(LONG,)
jshell> java.time.LocalDate.now().format($13)
$14 ==> "2019年1月17日"
And how to print it as a string.
I tried this but I get the date in (YYYMMMMDDD HHSSMM) format:
System.out.println(LocalDateTime.now());
What is the easiest way to get the current date in (YYYYMMDD) format?
is that what you are looking for?
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
System.out.println(LocalDate.now().format(formatter));
This does the trick but may not be the easiest:
import java.util.*;
import java.text.*;
class Test {
public static void main (String[] args) {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Date date = new Date();
System.out.println(dateFormat.format(date));
}
}
DateTimeFormatter.BASIC_ISO_DATE.format(LocalDate.now());
This is a very old question but gets me every time. There is a much simpler way now in one line:
String now = Instant.now().atZone(ZoneOffset.UTC).format(DateTimeFormatter.ISO_LOCAL_DATE);
System.out.println(now);
outputs: 2020-07-09
Just use: SimpleDateFormat
// Create an instance of SimpleDateFormat used for formatting
// the string representation of date (month/day/year)
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
// Get the date today using Calendar object.
Date today = Calendar.getInstance().getTime();
// Using DateFormat format method we can create a string
// representation of a date with the defined format.
String reportDate = df.format(today);
// Print what date is today!
System.out.println("Report Date: " + reportDate);
http://www.mkyong.com/java/how-to-convert-string-to-date-java/
I'm getting my object's createdAt timestamp back from parse.com as 2014-08-01T01:17:56.751Z. I have a class that converts it to relative time.
public static String timeAgo(String time){
PrettyTime mPtime = new PrettyTime();
long timeAgo = timeStringtoMilis(time);
return mPtime.format( new Date( timeAgo ) );
}
public static long timeStringtoMilis(String time) {
long milis = 0;
try {
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sd.parse(time);
milis = date.getTime();
} catch (Exception e) {
e.printStackTrace();
}
return milis;
}
The problem is that this parses the date wrongly. Right now the result says 4 decades ago and this very wrong. What I'm I doing wrong?
Your current date format "yyyy-MM-dd HH:mm:ss" does not work for the given example 2014-08-01T01:17:56.751Z. The format is missing the characters T and Z and the milliseconds.
Change it to:
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
to fix it.
Also check the examples in the JavaDoc of SimpleDateFormat, because it also shows the correct date format for your example: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html.
Expanding #Tom's answer:
The problem
When hardcoding 'Z', you assume that all dates were saved as UTC - which doesn't necessarily have to be the case.
The problem is that SimpleDateFormat does not recognize the literal 'Z'as an alias for UTC's '-0000' offset (For whatever reason, since it claims to be ISO-8601 compliant).
So you can't do
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
since this wrongly assumes all dates will always be written as in UTC, but you can't do
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
either, since this would not be able to parse the date when the literal 'Z' occurs.
Solution 1: Use javax.xml.bind.DatatypeConverter
This datatype converter actually is ISO8601 compliant and can be used as easy as
import javax.xml.bind.DatatypeConverter;
public Long isoToMillis(String dateString){
Calendar calendar = DatatypeConverter.parseDateTime(dateString);
return calendar.getTime().getTime();
}
If you use JAXB anyway, that would be the way to go.
Solution 2: Use conditional formats
final static String ZULUFORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
final static String OFFSETFORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
/* This is a utility method, so you want the calling method
* to be informed that something is wrong with the input format
*/
public static Long isoToMillis(String dateString) throws ParseException{
/* It is the default, so we should use it by default */
String formatString = ZULUFORMAT;
if(! dateString.endsWith("Z") ) {
formatString = OFFSETFORMAT;
}
SimpleDateFormat sd = new SimpleDateFormat(formatString);
return sd.parse(dateString).getTime();
}
If you don't already use JAXB, you might want to put this method into a utility class.