I made this snippet to show my problem:
import java.text.SimpleDateFormat;
public class Foo {
public static void main(String[] args) {
SimpleDateFormat formatter = new SimpleDateFormat("mm hh dd MM yyyy");
String date1 = "1412293500";
String date2 = "1412336700";
String dateString1 = formatter.format(Long.parseLong(date1 + "000"));
String dateString2 = formatter.format(Long.parseLong(date2 + "000"));
System.out.println(dateString1 + " " + dateString2);
}
}
date1
and date2
are expressed in seconds, so I'm expecting two different dates in output, but the dates are printed the same. I checked inside this online tool, and as you can see the dates are related to two different days.
How can I solve this?
In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.
We can use compareTo() function from Date class to compare the two dates. compareTo() function returns: 0 if both dates are equal.
In this very case you can just compare strings date1. compareTo(date2) . EDIT: However, the proper way is to use SimpleDateFormat : DateFormat f = new SimpleDateFormat("yyyy-mm-dd"); Date d1 = f.
The difference between your two timestamps is exactly 12 hours.
The h
identifier in SimpleDateFormat
formats the hours in AM/PM (1-12), so you actually do not output the real difference: the date was shifted from AM to PM.
Try with the k
or H
identifier which formats the hour in day as (1-24) or (0-23).
SimpleDateFormat formatter = new SimpleDateFormat("mm kk dd MM yyyy");
String date1 = "1412293500";
String date2 = "1412336700";
String dateString1 = formatter.format(Long.parseLong(date1 + "000"));
String dateString2 = formatter.format(Long.parseLong(date2 + "000"));
System.out.println(dateString1 + " " + dateString2); // prints 45 01 03 10 2014 45 13 03 10 2014
You could also output the AM/PM marker with the a
identifier like this:
SimpleDateFormat formatter = new SimpleDateFormat("mm hh dd MM yyyy aa");
String date1 = "1412293500";
String date2 = "1412336700";
String dateString1 = formatter.format(Long.parseLong(date1 + "000"));
String dateString2 = formatter.format(Long.parseLong(date2 + "000"));
System.out.println(dateString1 + " " + dateString2); // prints 45 01 03 10 2014 AM 45 01 03 10 2014 PM
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