How to convert current date into string in java?

2019-01-03 09:45发布

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

9条回答
SAY GOODBYE
2楼-- · 2019-01-03 10:16

Faster :

String date = FastDateFormat.getInstance("dd-MM-yyyy").format(System.currentTimeMillis( ));
查看更多
唯我独甜
3楼-- · 2019-01-03 10:22
// On the form: dow mon dd hh:mm:ss zzz yyyy
new Date().toString();
查看更多
男人必须洒脱
4楼-- · 2019-01-03 10:23

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.

查看更多
登录 后发表回答