147

How do I convert the current date into string in Java?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
user354299
  • 2,945
  • 5
  • 20
  • 10

9 Answers9

244
String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
Ian Purton
  • 15,331
  • 2
  • 27
  • 26
66
// GET DATE & TIME IN ANY FORMAT
import java.util.Calendar;
import java.text.SimpleDateFormat;
public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";

public static String now() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
return sdf.format(cal.getTime());
}

Taken from here

Itay Karo
  • 17,924
  • 4
  • 40
  • 58
30
// On the form: dow mon dd hh:mm:ss zzz yyyy
new Date().toString();
Zitrax
  • 19,036
  • 20
  • 88
  • 110
jasonmp85
  • 6,749
  • 2
  • 25
  • 41
  • 58
    Well sorry for overachieving. – jasonmp85 May 31 '10 at 10:25
  • 2
    The format used by that method is terrible. Also, your KVM’s current default time zone is implicitly applied, so your results will vary. And these troublesome classes are now legacy, supplanted by the java.time classes. See [Oracle Tutorial](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Aug 18 '17 at 15:51
24

Use a DateFormat implementation; e.g. SimpleDateFormat.

DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String data = df.format(new Date());
Josh Bowden
  • 5,735
  • 2
  • 25
  • 36
Adamski
  • 54,009
  • 15
  • 113
  • 152
  • FYI, these troublesome classes are now legacy, supplanted by the java.time classes. See [Oracle Tutorial](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Aug 18 '17 at 15:51
21

tl;dr

LocalDate.now()
         .toString() 

2017-01-23

Better to specify the desired/expected time zone explicitly.

LocalDate.now( ZoneId.of( "America/Montreal" ) )
         .toString() 

java.time

The modern way as of Java 8 and later is with the java.time framework.

Specify the time zone, as the date varies around the world at any given moment.

ZoneId zoneId = ZoneId.of( "America/Montreal" ) ;  // Or ZoneOffset.UTC or ZoneId.systemDefault()
LocalDate today = LocalDate.now( zoneId ) ;
String output = today.toString() ;

2017-01-23

By default you get a String in standard ISO 8601 format.

For other formats use the java.time.format.DateTimeFormatter class.


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?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

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

Faster :

String date = FastDateFormat.getInstance("dd-MM-yyyy").format(System.currentTimeMillis( ));
Johann Goulley
  • 405
  • 14
  • 25
1

Most of the answers are/were valid. The new JAVA API modification for Date handling made sure that some earlier ambiguity in java date handling is reduced.

You will get a deprecated message for similar calls.

new Date() // deprecated

The above call had the developer to assume that a new Date object will give the Date object with current timestamp. This behavior is not consistent across other Java API classes.

The new way of doing this is using the Calendar Instance.

new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime()

Here too the naming convention is not perfect but this is much organised. For a person like me who has a hard time mugging up things but would never forget something if it sounds/appears logical, this is a good approach.

This is more synonymous to real life

  1. We get a Calendar object and we look for the time in it. ( you must be wondering no body gets time from a Calendar, that is why I said it is not perfect.But that is a different topic altogether)
  2. Then we want the date in a simple Text format so we use a SimpleDateFormat utility class which helps us in formatting the Date from Step 1. I have used yyyy, MM ,dd as parameters in the format. Supported date format parameters

One more way to do this is using Joda time API

new DateTime().toString("yyyy-MM-dd")

or the much obvious

new DateTime(Calendar.getInstance().getTime()).toString("yyyy-MM-dd")

both will return the same result.

  • FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html), `java.util.Calendar`, and `java.text.SimpleTextFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [java.time](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes. Also, the [Joda-Time](http://www.joda.org/joda-time/) project is now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), with the team advising migration to java.time. – Basil Bourque May 08 '17 at 20:55
  • 1
    @BasilBourque That is what I meant in my answer, that the top voted answer is right but not relevant to a present day developer. Finally java will have a Clock class and Clock.getTime() would be much more sensible and real life imitating than Date or DateTime or Time classes. Java developers need to know that OOPS started as something which imitates real life scenarios. – Swapnil Vargaonkar May 12 '17 at 08:46
  • FYI, the `Clock` implementation in Java 8 is exactly the same as the legacy classes. Only in Java 9 does a new implementation arrive, capable of capturing the current moment with a resolution as fine as nanoseconds. – Basil Bourque Aug 18 '17 at 15:56
  • Yes that is the reason I wrote "finally" Java will have a Clock class which will imitate the real life scenario( OOPS concept) and show/capture( the way you would prefer saying it) the current moment. – Swapnil Vargaonkar Aug 21 '17 at 13:42
1

For time as YYYY-MM-dd

String time = new DateTime( yourData ).toString("yyyy-MM-dd");

And the Library of DateTime is:

import org.joda.time.DateTime;

  • And what library is `DateTime` from? An Answer on Stack Overflow should have some explanation as this site is meant to be more than a snippet library. – Basil Bourque Aug 18 '17 at 15:45
-3
public static Date getDateByString(String dateTime) {
        if(dateTime==null || dateTime.isEmpty()) {
            return null;
        }
        else{
            String modified = dateTime + ".000+0000";
            DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
            Date dateObj = new Date();
            Date dateObj1 = new Date();
            try {
                if (dateTime != null) {
                    dateObj = formatter.parse(modified);
                }

            } catch (ParseException e) {
                e.printStackTrace();
            }

            return dateObj;
        }

    }