I'm having trouble with the format
method of a SimpleDateFormat object.
The code in question is:
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(date);
Where "date" is a Date object created using a long int from Calendar.getTimeInMillis();
Calendar cal = Calendar.getInstance();
Date date = new Date(cal.getTimeInMillis());
Everything is working fine except the year portion of the string. When I pass the date, the string outputted looks like this:
0044-09-10 05:30:24
The date object that is passed is created from a long integer returned from:
Calendar.getTimeInMillis();
I believe the number returned from this method counts the milliseconds from Jan. 1st. 1970, which I'm thinking is the problem, but even if I add the number of milliseconds in 1970 years (lol, probably the wrong thing to do, but it was worth a shot :P), it still parses as 0044 in the year portion.
I've done numerous google searches and all seem to point simple issues in the string passed to the SimpleDateFormat constructor, so I'm at a loss here.
Any help is greatly appreciated.
Please let me know if any other information is needed and I will do my best to provide it.
Thanks again!
EDIT:
I figured I would explain the context a little more:
A technician will run a call, and on arriving to the site, will mark the call as "Started."
The app will then create a Calendar
instance and save the long int returned from Calendar.getTimeInMillis()
.
When the technician is finished with the call, he/she will mark the call as "Complete." Again, a Calendar
instance is created and the long int returned from Calendar.getTimeInMillis()
is saved.
This allows easy "call duration" calculation.
Now, when the closing form that the technician uses in the app is used, the long ints saved during the calls is passed to a Date
object, which is then passed to a SimpleDateFormat.format()
method.
This is where the issue arises. Thanks again, hope this helped.
To calculate duration between date/times, don't rely on subtracting milliseconds, it is highly unreliable.
If you're using Java 8, you should take advantage of the new java.time
API, for example...
LocalDateTime dt1 = LocalDateTime.of(2014, 9, 11, 10, 0);
LocalDateTime dt2 = LocalDateTime.of(2014, 9, 11, 12, 0);
Duration duration = Duration.between(dt1, dt2);
System.out.println(duration.toDays());
System.out.println(duration.toHours());
System.out.println(duration.toMinutes());
System.out.println(duration.getSeconds());
Which outputs...
0
2
120
7200
Take a look at Period and Duration for more details.
Alternatively, you could use JodaTime (which the java.time
is based off)
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