2
votes

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

11
The question does not really make sense: a Date is just a moment in time, it does not have a format.Henry
new Date() is already a Date, not a String.Alex Salauyou
You get the current date by new Date(). As I already commented earlier, a Date object does not carry a format. Formats only come into play when you convert the Date into a String.Henry
FYI, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes. Much of the java.time functionality is back-ported to Java 6 & Java 7 in the ThreeTen-Backport project. Further adapted for earlier Android in the ThreeTenABP project. See How to use ThreeTenABP….Basil Bourque

11 Answers

2
votes

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

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?

1
votes

Try this way

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

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

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());
1
votes

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.

0
votes

a parse method should be available to you. Use intellisense to check what methods your objects have :) Or simply look at the javadoc, most IDE's have an option to open the java files.

String dateString = "2016-01-01T00:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date d = sdf.parse(dateString);
0
votes

Try this:

LocalDateTime ldt = Instant.now()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDateTime()
0
votes

If you want String to Date conversion, you need to parse Date in String format using DateFormat. This is an example -

    String target = "2016-03-10T15:54:49";
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    Date result =  df.parse(target);
0
votes
public String getCurrentDateTime() {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        // get current date time with Date()
        Date date = new Date();
        return dateFormat.format(date);

    }
0
votes

Time Format should be same or else get time parser exception come

String dateString = "03/26/2012 11:49:00 AM";
    SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa");
    Date convertedDate = new Date();
    try {
        convertedDate = dateFormat.parse(dateString);
    } catch t(ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println(convertedDate);
0
votes

Yes u can :) you can convert back a String to a Date.

This method will help you: Date parse(String date);

It returns Date class object. You just have to pass the date in String format in this method.

import java.text.*;
import java.util.*;

class Test {
    public static void main(String[] args)  throws Throwable {

    String date = "2016-03-10T04:05:00";

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

    Date d = s.parse(date);

    System.out.println(d);
   }
}