• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

SimpleDateFormat Bug

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");
Posts: 1845
  • 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
Posts: 21997
Eclipse IDE Spring VI Editor Chrome Java Ubuntu 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.
Master Rancher
Posts: 4663
  • 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

What does a metric clock look like? I bet it is nothing like this tiny ad:
Thread Boost feature
    Bookmark Topic Watch Topic
  • New Topic