用Java获取当前日期和时间
时间:2020-01-09 10:35:26 来源:igfitidea点击:
在本文中,我们将介绍使用Java获取当前日期和时间的不同方法。我们正在使用的选项
- java.util.Date
- java.util.Calendar
- java.time.LocalDate-获取日期。
- java.time.LocalTime-获取时间。
- java.time.LocalDateTime-获取日期和时间。
- java.time.ZonedDateTime-如果我们也需要时区信息。
在这些类中,LocalDate,LocalTime,LocalDateTime和ZonedDateTime是Java 8新的Date and Time API中的类。
1.使用java.util.Date获取日期和时间
实例化Date对象时,它会被初始化,以使其代表分配它的日期和时间。
Date date = new Date(); System.out.println(date);
输出:
Thu Oct 10 16:42:21 IST 2019
使用SimpleDateFormat,我们可以格式化该日期。
public class FormatDate {
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
System.out.println(sdf.format(date));
}
}
输出:
10/10/2019 04:50:49.197
2.使用java.util.Calendar获取日期和时间
使用Calendar类的getInstance()静态方法,我们可以获取Calendar的实例。
public class FormatDate {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("MMM-dd-yyyy hh:mm:ss");
System.out.println(sdf.format(calendar.getTime()));
}
}
3.使用java.time.LocalDate
LocalDate表示ISO-8601日历系统中没有时区的日期。使用now()方法,我们可以从系统时钟的默认时区中获取当前日期。
对于格式化日期,可以使用Java 8中也添加的DateTimeFormatter类。
public class FormatDate {
public static void main(String[] args) {
// get date
LocalDate date = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
System.out.println(date.format(formatter));
}
}
输出:
10/10/2019
4.使用java.time.LocalTime
LocalTime表示ISO-8601日历系统中没有时区的时间,例如08:10:30。
使用now()方法可以从默认时区的系统时钟获取当前时间。
public class FormatDate {
public static void main(String[] args) {
// get time
LocalTime date = LocalTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm:ss a");
System.out.println(date.format(formatter));
}
}
输出:
05:11:31 PM
5.使用java.time.LocalDateTime
LocalDateTime表示ISO-8601日历系统中没有时区的日期时间,例如2007-12-03T10:15:30。
使用now()方法,我们可以在默认时区中从系统时钟获取当前日期时间。
public class FormatDate {
public static void main(String[] args) {
// get datetime
LocalDateTime dateTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
System.out.println(dateTime.format(formatter));
}
}
输出:
2019-10-10T17:14:41.098
6.使用java.time.ZonedDateTime
ZonedDateTime代表ISO-8601日历系统中带有时区的日期时间,例如2007-12-03T10:15:30 + 01:00欧洲/巴黎。如果需要区域偏移和时区,则可以使用ZonedDateTime实例。
public class FormatDate {
public static void main(String[] args) {
// get datetime
ZonedDateTime dateTime = ZonedDateTime.now();
//z=time-zone name, V=time-zone ID
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS z VV");
System.out.println(dateTime.format(formatter));
}
}
输出:
2019-10-10T17:22:31.958 IST Asia/Calcutta

