Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simpledateformat symmetrical formatting/parsing

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?

like image 213
wrm Avatar asked Nov 23 '25 18:11

wrm


1 Answers

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");
like image 106
Aleksandr M Avatar answered Nov 26 '25 08:11

Aleksandr M