Format a Date and returning a Date, not a String

23,373

Solution 1

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

Solution 2

tl;dr

ZonedDateTime.now()                                   // Capture the current moment as seen by the people of a region representing by the JVM’s current default time zone. 
    .format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )  // Generate a String representing that value using a standard format that omits any indication of zone/offset (potentially ambiguous).

java.time

The modern approach uses the java.time classes.

Capture the current moment in UTC.

Instant instant = Instant.now() ;

View that same moment through the wall-clock time used by the people of a particular region (a time zone).

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;  // Same moment, same point on the timeline, different wall-clock time.

You want to generate a string representing this value in a format that lacks any indication of time zone or offset-from-UTC. I do not recommend this. Unless the context where read by the user is absolutely clear about the implicit zone/offset, you are introducing ambiguity in your results. But if you insist, the java.time classes predefine a formatter object for that formatting pattern: DateTimeFormatter.ISO_LOCAL_DATE_TIME.

String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Solution 3

Try this way

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

Date date = sdf.parse("2016-03-10....");

Solution 4

To format a data field do this

Date today = new Date();
        //formatting date in Java using SimpleDateFormat
        SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        String date2= DATE_FORMAT.format(today);

        Date date;
        try {
            date = DATE_FORMAT.parse(date2);
             setDate(date); //make use of the date
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

The above works for me perfectly.

Solution 5

use my code, I hope it's works for you......

 SimpleDateFormat dateFormat= new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
 String str_date=dateFormat.format(new Date());
Share:
23,373
Don
Author by

Don

Updated on July 09, 2022

Comments

  • Don
    Don almost 2 years

    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