Java-日期与时间api
Java中时间的表达方式
Date
- java.util.Date类表示时间,不过由于对国际化支持有限,所以JDK1.1之后推荐使用java.util.Calendar类;
- java.util.Date类中很多构造方法和方法已经过时(Deprecated),不推荐使用,此处只学习两个没过时的构造方法;
方法声明 | 方法描述 |
---|---|
Date() | 使用当前时间构建Date对象; |
Date(long date) | 使用一个long值构建Date对象,参数是距离1970.1.1.00:00:00以来的毫秒数,时间戳 |
- java.util.Date类中方法
方法声明 | 方法描述 |
---|---|
public long getTime() | 返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数。 |
public boolean after(Date when) | 测试此日期是否在指定日期之后 |
public boolean before(Date when) | 测试此日期是否在指定日期之前。 |
public int compareTo(Date anotherDate) | 比较两个日期的顺序。如果参数日期等于此日期0; 如果这个日期在Date参数之前返回负数的值 ; 如果这个日期在Date参数之后返回正数的值。 |
public boolean equals(Object obj) | 比较两个日期的相等性 |
- 例子:
import java.util.Date; public class TestDate { public static void main(String[] args) { //当前日期和时间 Date date = new Date(); System.out.println(date); //传一个参的构造方法(参数为时间戳) Date date1 = new Date(2000/*1000毫秒 = 1秒*/);/*中国时区 : 东八区*/ System.out.println(date1); //当前日期的时间戳System.currentTimeMillis() System.out.println(System.currentTimeMillis()); Date date2 = new Date(System.currentTimeMillis()); System.out.println(date2); System.out.println("========================================"); System.out.println("date1的时间戳为:" + date1.getTime()); System.out.println(date.after(date1)); //true System.out.println(date.before(date1)); //fasle //1表示 date比date1日期要大 , -1表示date比date1日期要小 , 0相等 System.out.println(date.compareTo(date1)); // 1 System.out.println(date.compareTo(date2)); // -1 } } /* Sat Apr 09 16:37:24 CST 2022 Thu Jan 01 08:00:02 CST 1970 1649493444274 Sat Apr 09 16:37:24 CST 2022 ======================================== date1的时间戳为:2000 true false 1 -1 */
Calendar
- JDK1.1版本开始,增加Calendar类,建议使用Calendar类代替Date类;
- Calendar是抽象类,不能直接使用new创建对象;
- Calendar类中定义了获得实例的方法:
方法声明 | 方法描述 |
---|---|
static Calendar getInstance() | 使用默认时区和语言环境获得日历对象; |
static Calendar getInstance(Locale aLocale) | 使用指定的语言环境获得日历对象; |
static Calendar getInstance(TimeZone zone) | 使用指定的时区获得日历对象; |
static Calendar getInstance(TimeZone zone, Locale aLocale) | 使用指定的时区及语言环境获得日历对象; |
方法声明 | 方法描述 |
---|---|
void set(int field, int value) | 为指定的日历字段设定值;月份从0开始 |
void set(int year, int month, int date) | 为年月日设定值; |
void set(int year, int month, int date, int hourOfDay, int minute) | 为年月日时分设定值; |
void set(int year, int month, int date, int hourOfDay, int minute, int second) | 为年月日时分秒设定值; |
方法声明 | 方法描述 |
---|---|
Date getTime() | 将日历对象转换为Date对象返回; |
int get(int field) | 根据字段名称,返回该字段的值; |
- 对Calendar的字段赋值后,可以对其值进行修改;
方法声明 | 方法描述 |
---|---|
void add(int field, int amount) | 将日历对象转换为Date对象返回; |
- 例子:
import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; public class TestCalendar { public static void main(String[] args) { //获取默认时区和语言环境 Calendar calendar1 = Calendar.getInstance(); System.out.println(calendar1); //指定时区和语言环境 Calendar calendar2 = Calendar.getInstance(TimeZone.getTimeZone("Asia/Shanghai"), Locale.ENGLISH); System.out.println(calendar2); //set calendar1.set(Calendar.YEAR,2000); calendar1.set(Calendar.MONTH,8); /*0到11*/ calendar1.set(Calendar.DATE,5); calendar1.set(Calendar.HOUR_OF_DAY,17); calendar1.set(Calendar.MINUTE,8); calendar1.set(Calendar.SECOND,8); calendar2.set(2000,8,5,14,58,58); //get Date time1 = calendar1.getTime(); System.out.println(time1); Date time2 = calendar2.getTime(); System.out.println(time2); System.out.println(calendar1.get(Calendar.YEAR)); System.out.println(calendar1.get(1)); //add calendar1.add(Calendar.YEAR,17); System.out.println(calendar1.getTime()); } } /* java.util.GregorianCalendar[time=1649494142312,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=29,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2022,MONTH=3,WEEK_OF_YEAR=15,WEEK_OF_MONTH=2,DAY_OF_MONTH=9,DAY_OF_YEAR=99,DAY_OF_WEEK=7,DAY_OF_WEEK_IN_MONTH=2,AM_PM=1,HOUR=4,HOUR_OF_DAY=16,MINUTE=49,SECOND=2,MILLISECOND=312,ZONE_OFFSET=28800000,DST_OFFSET=0] java.util.GregorianCalendar[time=1649494142332,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=29,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2022,MONTH=3,WEEK_OF_YEAR=15,WEEK_OF_MONTH=2,DAY_OF_MONTH=9,DAY_OF_YEAR=99,DAY_OF_WEEK=7,DAY_OF_WEEK_IN_MONTH=2,AM_PM=1,HOUR=4,HOUR_OF_DAY=16,MINUTE=49,SECOND=2,MILLISECOND=332,ZONE_OFFSET=28800000,DST_OFFSET=0] Tue Sep 05 17:08:08 CST 2000 Tue Sep 05 14:58:58 CST 2000 2000 2000 Tue Sep 05 17:08:08 CST 2017 */
日期与时间数据的格式化方法
- 实际编程中,往往需要对时间用不同的格式进行展示;
- SimpleDateFormat中定义了对时间进行格式化的方法;该类继承了抽象父类DateFormat,某些方法在父类中定义,查阅API文档时注意;
- 可以自定义一个模式字符串来构建SimpleDateFormat对象
方法声明 | 方法描述 |
---|---|
SimpleDateFormat(String pattern) | 使用模式字符串创建对象; |
SimpleDateFormat(String pattern, Locale locale) | 使用模式字符串和区域信息创建对象; |
方法声明 | 方法描述 |
---|---|
String format(Date date) | 把date进行格式化; |
yyyy:年 |
- 在实际编程中,往往一些时间内容都是通过用户输入获得,得到的是字符串,需要解析成日期时间类型进行处理;
- SimpleDateFormat类不仅能够格式化时间,还能解析时间字符串;
方法声明 | 方法描述 |
---|---|
public Date parse(String source) throws ParseException | 把字符串转换成Date对象,如果格式不匹配抛出转换异常; |
- 例子:
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class TestSimpleDateFormat { public static void main(String[] args) { dateToString(); stringToDate(); } public static void dateToString() { Date date = new Date(); Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.DATE, 1); Date date1 = calendar.getTime(); //定义格式(模式字符串) String pattern = "yyyy年MM月dd日 HH时mm分ss秒"; String pattern1 = "yy-M-d H-m-s"; //构造方法传入格式参数 SimpleDateFormat sdf = new SimpleDateFormat(pattern); String format = sdf.format(date); System.out.println(format); SimpleDateFormat sdf1 = new SimpleDateFormat(pattern1); String format1 = sdf1.format(date1); System.out.println(format1); } public static void stringToDate() { String pattern = "yyyy年MM月dd日 HH时mm分ss秒"; SimpleDateFormat sdf = new SimpleDateFormat(pattern); String strDate = "2000年9月5日 17时5分26秒"; try { Date date = sdf.parse(strDate); System.out.println(date); System.out.println(date.getTime()); //把时间戳存在数据库里 } catch (ParseException e) { e.printStackTrace(); } } } /* 2022年04月09日 16时58分33秒 22-4-1 16-58-33 Tue Sep 05 17:05:26 CST 2000 968144726000 */
- JDK8中定义了java.time.LocalDate,用来表示日期,默认格式是yyyy-MM-dd;该类不包含时间信息;
- 常用的获得LocalDate对象的方式如下:
方法声明 | 方法描述 |
---|---|
static LocalDate now() | 使用当前日期生成LocalDate对象; |
static LocalDate of(int year, int month, int dayOfMonth) | 使用年月日数值生成LocalDate对象; |
- LocalDate类中部分方法如下
方法声明 | 方法描述 |
---|---|
int getYear() | 返回年字段值; |
int getMonthValue() | 返回月字段值; |
int getDayOfMonth() | 返回天字段值 |
static LocalDate parse(CharSequence text) | 将字符串转换成LocalDate对象; |
- 例子:
import java.time.LocalDate; public class TestLocalDate { public static void main(String[] args) { //now()静态方法 获取当前日期的LocalDate对象 LocalDate now = LocalDate.now(); System.out.println(now); //of()静态方法 获取指定日期的LocalDate对象 LocalDate localDate = LocalDate.of(2000, 9, 5); System.out.println(localDate); //获取当前时间是当月的第几天 System.out.println(now.getDayOfMonth()); //获取当前时间是一周内的第几天 System.out.println(now.getDayOfWeek()); //获取当前时间是一年的第几天 System.out.println(now.getDayOfYear()); System.out.println(now.getMonth()); //yyyy-MM-dd String strLocalDate = "2000-08-08"; LocalDate maLocalDate = LocalDate.parse(strLocalDate); System.out.println(maLocalDate); } } /* 2022-04-09 2000-09-05 9 SATURDAY 99 APRIL 2000-08-08 */
- LocalDate类只表示日期,JDK8中定义了新类LocalTime用来表示时间,用法与LocalDate类似;:
- 例子:
import java.time.LocalTime; import java.time.temporal.ChronoField; public class TestLocalTime { public static void main(String[] args) { //now() LocalTime now = LocalTime.now(); System.out.println(now); //of() LocalTime localTime = LocalTime.of(17, 5, 26); System.out.println(localTime); System.out.println(now.getHour()); System.out.println(now.getMinute()); System.out.println(now.getSecond()); //获取当前时间是一分钟内的第几秒 System.out.println(now.get(ChronoField.SECOND_OF_MINUTE)); //获取当前时间是一天内的第几分钟 System.out.println(now.get(ChronoField.MINUTE_OF_DAY)); System.out.println(now.get(ChronoField.HOUR_OF_DAY)); System.out.println(now.get(ChronoField.MINUTE_OF_HOUR)); //parse,参数格式是 HH:mm:ss LocalTime parseLocalTime = LocalTime.parse("17:09:58"); System.out.println(parseLocalTime); } } /* 17:09:14.888 17:05:26 17 9 14 14 1029 17 9 17:09:58 */
- LocalDate类只表示日期,LocalTime只表示时间,JDK8中还定义了一个LocalDateTime类,同时包含日期与时间,用法与LocalDate及LocalTime类似;
- 例子:
import java.time.LocalDateTime; public class TestLocalDateTime { public static void main(String[] args) { //now() LocalDateTime now = LocalDateTime.now(); System.out.println(now); //of() LocalDateTime of = LocalDateTime.of(2000, 9, 5, 17, 5, 26); System.out.println(of); System.out.println(now.getDayOfMonth()); System.out.println(now.getHour()); //parse 默认格式 "yyyy-MM-ddTHH:mm:ss" LocalDateTime parse = LocalDateTime.parse("2022-09-03T17:05:26"); System.out.println(parse); } } /* 2022-04-09T17:11:38.499 2000-09-05T17:05:26 9 17 2022-09-03T17:05:26 */
- 对于格式化及解析,JDK8中使用DateTimeFormatter类实现;
- 获得DateTimeFormatter对象的部分方法:
方法声明 | 方法描述 |
---|---|
static DateTimeFormatter ofPattern(String pattern) | 指定模式字符串,生成DateTimeFormatter对象 |
static DateTimeFormatter ofPattern(String pattern, Locale locale) | 指定模式字符串及区域信息,生成DateTimeFormatter对象 |
- LocalDate、LocalTime、LocalDateTime类都可以使用DateTimeFormatter对象进行格式化;
- 另外,LocalDate、LocalTime、LocalDateTime类都定义了parse方法,可以使用DateTimeFormatter对象把字符串按照指定的格式转换成时间日期类型对象;
- 例子:
import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.format.DateTimeFormatter; public class MyTestDateTimeFormatter { public static void main(String[] args) { //定义格式(模式字符串) String pattern = "yyyy年MM月dd日 HH时mm分ss秒"; String pattern1 = "yyyyMMdd"; String pattern2 = "yyyy/MM/dd"; String pattern3 = "HH:mm:ss"; //ofPatter静态方法获取DateTimeFormatter对象 DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern); DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern(pattern1); DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern(pattern2); DateTimeFormatter dtf3 = DateTimeFormatter.ofPattern(pattern3); //获取对象 LocalDateTime now = LocalDateTime.now(); LocalDate now1 = LocalDate.parse("20000905", dtf1);//格式要一样 LocalDate now2 = LocalDate.now(); LocalTime now3 = LocalTime.parse("09:05:08", dtf3); String format = dtf.format(now); String format2 = dtf2.format(now2); System.out.println(format); System.out.println(now1); System.out.println(format2); System.out.println(now3); } } /* 2022年04月09日 17时17分37秒 2000-09-05 2022/04/09 09:05:08 */
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话