Formatting DatesString pattern = "yyyy-MM-dd"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); String date = simpleDateFormat. format(new Date()); System. out. println(date);
String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
// 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
// On the form: dow mon dd hh:mm:ss zzz yyyy
new Date().toString();
Use a DateFormat
implementation; e.g. SimpleDateFormat
.
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String data = df.format(new Date());
LocalDate.now()
.toString()
2017-01-23
Better to specify the desired/expected time zone explicitly.
LocalDate.now( ZoneId.of( "America/Montreal" ) )
.toString()
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.
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.
Faster :
String date = FastDateFormat.getInstance("dd-MM-yyyy").format(System.currentTimeMillis( ));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With