Jane Makedonskaya
Jane Makedonskaya

Reputation: 43

How can i get data in format "YYYY-MM-DD 00:00:00.0" using class Date?

How can i get data in format "YYYY-MM-DD 00:00:00.0" using class Date (it's extremly important to use exactly this class)?

I tried to do everything i can think of:

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
df.format(date)

and

String pattern = "yyyy-MM-dd HH:mm:ss.S";
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
Date date = format.parse("2011-01-18 00:00:00.0");
} catch (ParseException e) {
e.printStackTrace();
}

byt when i print date using logger i get this format "Tue Sep 30 00:00:00 MSK 1913".

Upvotes: 0

Views: 18037

Answers (4)

Nallamachu
Nallamachu

Reputation: 1488

I hope the below one will solve your problem when you need to do for dynamic dates.

Date today = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
String formattedDate = sdf.format(today);
System.out.println(formattedDate);
//Above line output (formatted String object) is 2017-12-29 00:00:00
System.out.println(format.format(formattedDate));
//Above line output(parsed Date object) is Fri Dec 29 00:00:00 IST 2017

For Date object you can't get the output as yyyy-MM-dd 00:00:00, but you will get this format in String object type.

Upvotes: 0

Kent
Kent

Reputation: 195079

You are confused by Date.toString() and SimpleDateFormat.format()

An object of Date (java.util.Date) has no format information. If you call date.toString(), (which is called by your logger), you got default representation of this object, you have seen what it is.

However, SimpleDateFormat.format() will give you a string as return value, this value will format the Date object with a pattern defined by SimpleDateFormat.

In your code, you first parsed the string, with certain pattern, to get the date object. If it was successful, you got the Date object, here, for this date object, you don't have any format information, even if you have defined a pattern to parse the input string. If you want to print/output (to string again) the date object, you have to use the SimpleDateFormat.format() method.

Upvotes: 1

Niels Bech Nielsen
Niels Bech Nielsen

Reputation: 4859

Are you sure you want the hours, minutes, secs to be zeroes?

Or do you mean the pattern yyyy-MM-dd HH:mm:ss ?

The date class is always independent of the formatting. It only needs to be translated when you print it, like this:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String out = df.format(date)
System.out.println(out);

Or do you want to strip the time out of the date object? or something.

Upvotes: 1

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35557

Try this

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
    Date date = format.parse("2011-01-18 00:00:00.0");
    System.out.println(format.format(date));

Upvotes: 5

Related Questions