• Post Reply Bookmark Topic Watch Topic
  • New Topic

SimpleDateFormat Bug  RSS feed

 
SumitPal Pal
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I ran into this problem in Hive - using unix_timestamp -- which internally uses SimpleDateFormat Class

So I wrote this simple - Code
I am entering - "12/26/2014 1:00:00 PM" - as the time format and the pattern is - MM/DD/YYYY hh:mm:ss aaa
The output I am getting is - Sun Dec 29 13:00:00 EST 2013

Any thoughts
Python code works fine
// datetime.datetime.strptime("12/26/2014 1:00:00 PM", "%m/%d/%Y %I:%M:%S %p")
//datetime.datetime(2014, 12, 26, 13, 0)


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class SimpleDateFormatExample
{
public static void main(String[] args) throws Exception
{
Date curDate = new Date();
SimpleDateFormat format = new SimpleDateFormat();
String DateToStr = "12/26/2014 1:00:00 PM";
format = new SimpleDateFormat("MM/DD/YYYY hh:mm:ss aaa");
System.out.println(format.parse(DateToStr));
}
}
 
Stefan Evans
Bartender
Posts: 1837
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please UseCodeTags when posting code

Date format strings in java are actually case sensitive.

Try "MM/dd/yyyy hh:mm:ss aaa"

only the M is capital to distinguish Month from minute

Y actually refers to a "week year". See java.text.SimpleDateFormat
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is indeed a difference between Y and y, M and m, D and d, H and h, etc. This is all documented on http://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html.

Apart from YYYY instead of yyyy, you need dd instead of DD because D means the day of the year, not the day of the month.
 
Dave Tolls
Ranch Foreman
Posts: 3068
37
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Any problems with the format supplied aside, the above code is not doing what you think it is.

It is parsing the String into a Date, and then inside println it is calling the toString() method on Date which returns the format you see.
Indeed, from the JavaDoc of Date.toString():

Converts this Date object to a String of the form:
dow mon dd hh:mm:ss zzz yyyy
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!