user354299
user354299

Reputation: 2995

How to convert current date into string in java?

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

Upvotes: 151

Views: 279388

Answers (9)

Basil Bourque
Basil Bourque

Reputation: 338211

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.

Upvotes: 21

user8483918
user8483918

Reputation:

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;

Upvotes: 1

Ganesh Reddy
Ganesh Reddy

Reputation: 9

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

    }

Upvotes: -3

Swapnil Vargaonkar
Swapnil Vargaonkar

Reputation: 21

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.

Upvotes: 1

Adamski
Adamski

Reputation: 54697

Use a DateFormat implementation; e.g. SimpleDateFormat.

DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String data = df.format(new Date());

Upvotes: 24

jasonmp85
jasonmp85

Reputation: 6817

// On the form: dow mon dd hh:mm:ss zzz yyyy
new Date().toString();

Upvotes: 30

Johann Goulley
Johann Goulley

Reputation: 415

Faster :

String date = FastDateFormat.getInstance("dd-MM-yyyy").format(System.currentTimeMillis( ));

Upvotes: 9

Ian Purton
Ian Purton

Reputation: 15891

String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());

Upvotes: 249

Itay Karo
Itay Karo

Reputation: 18286

// 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

Upvotes: 67

Related Questions