3

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

Talha
  • 903
  • 8
  • 31
Don
  • 977
  • 3
  • 10
  • 28
  • 5
    The question does not really make sense: a `Date` is just a moment in time, it does not have a format. – Henry Mar 10 '16 at 10:26
  • 1
    `new Date()` is already a `Date`, not a `String`. – Alex Salauyou Mar 10 '16 at 10:27
  • 2
    Possible duplicate of [How to convert String to Date format in android](http://stackoverflow.com/questions/25460965/how-to-convert-string-to-date-format-in-android) – Tom Mar 10 '16 at 10:28
  • 2
    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 Mar 10 '16 at 12:51
  • 1
    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*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes. Much of the *java.time* functionality is back-ported to Java 6 & Java 7 in the [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/) project. Further adapted for earlier Android in the [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP) project. See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706). – Basil Bourque Apr 13 '18 at 00:54
  • Use `LocalDateTime` from `java.time`, the modern Java date and time API. Just like `Date` it hasn’t got any format, but its `toString` method produces the format you asked for (the format is called ISO 8601). Isn’t that at least something? – Ole V.V. Jun 08 '18 at 13:11

11 Answers11

3

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);
Kevin Cruijssen
  • 9,153
  • 9
  • 61
  • 135
  • 1
    Hi Kevin, this looks promising, unfortunately I don't get access to the method getFormat with DateTimeFormat. I have imported: import org.joda.time.format.DateTimeFormat; – Don Mar 10 '16 at 11:16
  • @Don Ah, I'm so sorry, I use the same code in a project I'm currently working on, but there I have to use the GWT for most default Java methods/classes..(PS / irrelevant: The import I've used is `import com.google.gwt.i18n.client.DateTimeFormat;`) I've edited my answer so it now uses a `SimpleDateFormat` instead. The rest of the code and the usage should still be the same. – Kevin Cruijssen Mar 10 '16 at 14:26
  • Hello Kevin, thanks for your edit, I can use your class now. Unfortunately, there is something wrong, here is what I log: formattedDate == 2016-03-11T09:20:10.650 convertedDate == Fri Mar 11 09:20:10 CET 2016 So the final output is not formatted according to the desired format. Maybe it is because it is twice formatted so it goes back to the initial default format? – Don Mar 11 '16 at 08:28
  • @Don I think you misunderstand how dates work.. When you simply try to print a Date: `System.out.println(new Date());` it will print the date in the default format from the PCs settings. If you want to print it in a format of your own, you use the `SimpleDateFormat`. A Date-object (like the `Date convertedDate` in my answer) doesn't have any format whatsoever. Only when printing you can give it a format (with `SimpleDateFormat`) or print it in the PC's default format (which is what you did by simply calling `System.out.println("convertedDate == " + convertedDate);` – Kevin Cruijssen Mar 11 '16 at 09:24
  • @delive Do you have a question?.. :S – Kevin Cruijssen Jan 30 '18 at 13:13
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?

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
1

Try this way

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

Date date = sdf.parse("2016-03-10....");
Aditya Vyas-Lakhan
  • 13,409
  • 16
  • 61
  • 96
jonhid
  • 2,075
  • 1
  • 11
  • 18
1

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());
Gaurav Rawal
  • 218
  • 1
  • 6
1

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.

rocket
  • 253
  • 1
  • 2
  • 13
  • Does it give you the requested `Date` with the requested format and not a `String`? In any case please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). Yes, you can use it on Android. For older Android see [How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project). – Ole V.V. Jun 08 '18 at 13:07
0

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);
Martin Hansen
  • 2,033
  • 1
  • 18
  • 34
  • Thanks for your answer Martin. In your solution, shall I use Long date1 = (new Date().getTime()); String dateString = date1.toString(); as the initial String before formatting? – Don Mar 10 '16 at 10:27
  • If you just want a `date` object for current time, why not just use `Date d = new Date()` then you already have your `Date` object? I'm not really sure what your question really is. The `toString()`method of `Date` is not formatted in your requested pattern i think, so that will not work. – Martin Hansen Mar 10 '16 at 10:31
  • Maybe I am missing something, all the answers including yours start from a static String date, whereas I need the current time. How can I use sdf.parse(dateString); with dateString being the String of the current Time? Sorry if I am mistaken somewhere – Don Mar 10 '16 at 10:40
  • if you just need the current time, just use `Date d = new Date()`. – Martin Hansen Mar 10 '16 at 10:49
  • this will return something like "Thu Mar 10 11:50:26 CET 2016" which is not the format I need – Don Mar 10 '16 at 10:51
  • then format it, like you said you knew how to in your post, with `SimpleDateFormat` ? :) – Martin Hansen Mar 10 '16 at 10:53
  • This will return a **String** not a Date – Don Mar 10 '16 at 10:54
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/105889/discussion-between-martin-hansen-and-don). – Martin Hansen Mar 10 '16 at 10:54
0

Try this:

LocalDateTime ldt = Instant.now()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDateTime()
Prashant
  • 4,775
  • 3
  • 28
  • 47
  • Correct code, but not a good idea. A `LocalDateTime` purposely lacks any concept of time zone or offset-from-UTC. So its use here is throwing away valuable information (the zone/offset). – Basil Bourque Apr 13 '18 at 00:56
0

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);
RSatpute
  • 59
  • 1
  • 1
  • 8
0
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);

    }
Rohit Heera
  • 2,709
  • 2
  • 21
  • 31
0

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);
Madvesha k
  • 11
  • 3
0

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);
   }
}
António Ribeiro
  • 4,129
  • 5
  • 32
  • 49