简体   繁体   中英

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".

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));

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM