1

There is a simple problem of Date Format Conversion. In java when we print date object its in this format "Tue Nov 13 18:34:35 PKT 2012" But I want this date to be shown in this format "2012-11-13 18:34:35" with in Date object. No string is required. Only Date object is needed in above format. Can any one help me. I am using

Date d = new Date();  
SimpleDateFormat sdf =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
Date formattedDate = sdf.parse(d.format(sdf)); 
Ashr Raza
  • 31
  • 2
  • 4
  • 1
    A `java.util.Date` is just a date, which means that there's no *format*, just data. You format a date when you want to print/write it, and that using for example the `java.text.SimpleDateFormat#format()` method. – sp00m Nov 13 '12 at 15:52
  • 1
    http://stackoverflow.com/questions/12300651/convert-string-to-date-in-java-in-format-2012-07-27/12300726#12300726 – mre Nov 13 '12 at 15:54

2 Answers2

3

But I want this date to be shown in this format "2012-11-13 18:34:35" with in Date object. No string is required.

The format you talk about is a string. If no string is required, then your first requirement goes away completely. You want the date to be shown, which means a string is required.

A Date has no concept of a format. It's just a number of milliseconds since the Unix epoch. There's no information within Date which controls the format.

Just use SimpleDateFormat, adjusting it to whatever format - and calendar, and time zone, and locale - you want. Don't waste time trying to change the Date itself, because you won't get anywhere. Treat Date.toString() as a diagnostic convenience and nothing more.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

I think you are confused. Formatting is only for display purpose, not for computation purpose. Date() object doesn't represent format, It is number of milliseconds of epoch time. Using SimpleDateFormat class format() method you can format the date and print as you wish.

kosa
  • 65,990
  • 13
  • 130
  • 167