Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

java - Format a Date and returning a Date, not a String

I need to get the Date of the current time with the following format "yyyy-MM-dd'T'HH:mm:ss"

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");   

I know how to format a Date using SimpleDateFormat. At the end I get a String. But I need to get the formatted Date, not String, and as far as I know, I cannot convert back a String to a Date, can I?

If I just return the Date, it is a Date but it is not properly formatted:

Timestamp ts = new Timestamp(new Date().getTime()); 

EDIT: Unfortunately I need to get the outcome as a Date, not a String, so I cannot use sdf.format(New Date().getTime()) as this returns a String. Also, the Date I need to return is the Date of the current time, not from a static String. I hope that clarifies

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

But I need to get the formatted Date, not String, and as far as I know, I cannot convert back a String to a Date, can I?

Since you know the DateTime-Format, it's actually pretty easy to format from Date to String and vice-versa. I would personally make a separate class with a string-to-date and date-to-string conversion method:

public class DateConverter{

    public static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

    public static Date convertStringToDate(final String str){
        try{
            return DATE_FORMAT.parse(str);
        } catch(Exception ex){
            //TODO: Log exception
            return null;
        }
    }

    public static String convertDateToString(final Date date){
        try{
            return DATE_FORMAT.format(date);
        } catch(Exception ex){
            //TODO: Log exception
            return null;
        }
    }
}

Usage:

// Current date-time:
Date date = new Date();

// Convert the date to a String and print it
String formattedDate = DateConverter.convertDateToString(date);
System.out.println(formattedDate);

// Somewhere else in the code we have a String date and want to convert it back into a Date-object:
Date convertedDate = DateConverter.convertStringToDate(formattedDate);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...