Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format a Date and returning a Date, not a String

Tags:

java

date

android

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

like image 593
Don Avatar asked Oct 25 '25 06:10

Don


1 Answers

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);
like image 70
Kevin Cruijssen Avatar answered Oct 27 '25 20:10

Kevin Cruijssen