I am using the code below on Mac OSX 10.10.2 and it's behaving strangely.
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringToDate {
public static void main(String[] args) throws Exception {
String dateInString = "23/Oct/2015";
DateFormat formatter = new SimpleDateFormat("dd/MMM/YYYY");
Date date = formatter.parse(dateInString);
System.out.println(date);
}
}
Output on Mac:
Sun Dec 28 00:00:00 CST 2014
Output on Windows: Fri Oct 23 00:00:00 CDT 2015
Why is the Mac output wrong?
Y
is for the week year. Usey
for the year.Also, make sure the DateFormat's locale is the right one.
EDIT:
A Date has millisecond precision, so if you want nanosecond precision, you shouldn't use Date and SimpleDateFormat.
S is for milliseconds. Since you tell SimpleDateFormat that the last part of the string is milliseconds, it parses it as that: 545000000 milliseconds (i.e. a bit more than 6 days, which explains the difference between the input and the output).
To get an accurate result, to the millisecond, remove the last 6 characters of the string, and use the pattern "dd-MMM-yyyy-HH.mm.ss.SSS".