DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");Date date = new Date();System.out.println(dateFormat.format(date));
或
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");Calendar cal = Calendar.getInstance();System.out.println(dateFormat.format(cal.getTime()));
import java.util.Date;
class Demostration{public static void main(String[]args){Date date = new Date(); // date objectSystem.out.println(date); // Try to print the date object}}
1.2如何使用getTime()方法
import java.util.Date;public class Main {public static void main(String[]args){Date date = new Date();long timeInMilliSeconds = date.getTime();System.out.println(timeInMilliSeconds);}}
Instant.now() // Capture the current moment in UTC, with a resolution of nanoseconds. Returns a `Instant` object.
…或者…
ZonedDateTime.now( // Capture the current moment as seen in…ZoneId.of( "America/Montreal" ) // … the wall-clock time used by the people of a particular region (a time zone).) // Returns a `ZonedDateTime` object.
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");Date date = new Date();System.out.println(dateFormat.format(date)); //2016/11/16 12:08:43
对于java.util.日历,使用Calendar.get实例()
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");Calendar cal = Calendar.getInstance();System.out.println(dateFormat.format(cal)); //2016/11/16 12:08:43
java.time.LocalDateTime,使用LocalDateTime.now()
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");LocalDateTime now = LocalDateTime.now();System.out.println(dtf.format(now)); //2016/11/16 12:08:43
import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;public class CurrentTimeDateCalendar {public static void getCurrentTimeUsingDate() {Date date = new Date();String strDateFormat = "hh:mm:ss a";DateFormat dateFormat = new SimpleDateFormat(strDateFormat);String formattedDate= dateFormat.format(date);System.out.println("Current time of the day using Date - 12 hour format: " + formattedDate);}public static void getCurrentTimeUsingCalendar() {Calendar cal = Calendar.getInstance();Date date=cal.getTime();DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");String formattedDate=dateFormat.format(date);System.out.println("Current time of the day using Calendar - 24 hour format: "+ formattedDate);}}