3

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?

Aleksandr M
  • 24,264
  • 12
  • 69
  • 143
wrm
  • 1,898
  • 13
  • 24
  • Can you explain what you are using week year `YYYY` and why stripping off the seconds part? You cannot achieve the same result with these two things... – Codebender Sep 25 '15 at 09:51

2 Answers2

1

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");
Community
  • 1
  • 1
Aleksandr M
  • 24,264
  • 12
  • 69
  • 143
0

Try thi by correcting the cases of MMM and HH,

SimpleDateFormat sdf = new SimpleDateFormat("MMM d, yyyy 'at' HH:mm:ss.a`Z`");
GregorianCalendar cal = new GregorianCalendar(Locale.US);
sdf.setTimeZone(cal.getTimeZone())
sdf.parse(sdf.format(1435271907000L)).getTime() == 1435271907000L

I hope this will work.

Guna
  • 316
  • 5
  • 18