I try to format a timestamp using a SimpleDateFormat and also I try to use the same format to parse such a formatted date:
SimpleDateFormat sdf = new SimpleDateFormat("MMM d, YYYY 'at' hh:mma z");
GregorianCalendar cal = new GregorianCalendar(Locale.US);
sdf.setTimeZone(cal.getTimeZone())
sdf.parse(sdf.format(1435271907000L)).getTime() == 1435271907000L
the last expression is false, the actual result is 1419806280000L
So how is it possible to achive a symmetrical dateTimeFormat parsing/formatting behaviour?
First of all there is no seconds in your format pattern, so your date's seconds will be initialized to 0. Second: YYYY is different from yyyy.
Add ss to your pattern and change YYYY to yyyy.
SimpleDateFormat sdf = new SimpleDateFormat("MMM d ss, yyyy 'at' hh:mma z");
String f = sdf.format(1435271907000L);
Date d = sdf.parse(f);
System.out.println(d.getTime() == 1435271907000L);
Note it will also print false for time with milliseconds > 0 (e.g. 1435271907001L). If you need milliseconds precision then you need to add milliseconds SSS to your pattern as well.
SimpleDateFormat sdf = new SimpleDateFormat("MMM d ss SSS, yyyy 'at' hh:mma z");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With