时间API
一、JDK8(-)时间类
1.Date类
表示时间的类
-
代表的是日期和时间
构造器 说明 public Date() 创建一个Date对象,代表的是系统当前此刻日期时间。 public Date(long time) 把时间毫秒值转换成Date日期对象 import java.util.Date; public class Test { public static void main(String[] args) { Date d1 = new Date(); System.out.println(d1); Date d2 = new Date(1000L); System.out.println(d2); } } //运行结果: /* Fri Apr 07 22:11:07 CST 2023 Thu Jan 01 08:00:01 CST 1970 */
-
常见方法
常见方法 说明 public long getTime() 返回从1970年1月1日 00:00:00走到此刻的总的毫秒数 public void setTime(long time) 设置日期对象的世界为当前时间毫秒值对应的世界 import java.util.Date; public class Test { public static void main(String[] args) { Date d1 = new Date(); System.out.println(d1.getTime()); Date d2 = new Date(1000L); System.out.println(d2.getTime()); } } //运行结果: /* 1680876952496 1000 */
2.SimpleDateFormat类
-
用于日期格式化
构造器 说明 public SimpleDateFormat() 构造一个SimpleDateFormat,使用默认格式 public SimpleDateFormat(String pattern) 构造一个SimpleDateFormat,使用指定的格式 格式化方法 说明 public final String format(Date date) 将日期格式化成日期/时间字符串 public final Date parse(String pattern) 将字符串解析为日期类型 import java.text.SimpleDateFormat; import java.util.Date; public class Test { public static void main(String[] args) { //默认模式 SimpleDateFormat simpleDateFormat = new SimpleDateFormat(); //手动指定模式 SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); Date date = new Date(); //将日期对象,转换为字符串 String result = simpleDateFormat.format(date); String result2 = simpleDateFormat2.format(date); System.out.println(result); System.out.println(result2); } } //运行结果: /* 2023/4/7 下午11:14 2023年04月07日 23:14:41 */
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Test { public static void main(String[] args) throws ParseException { String today = "2023年4月7日"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日"); Date date = simpleDateFormat.parse(today); System.out.println(date); } } //运行结果: /* Fri Apr 07 00:00:00 CST 2023 */
例子:
需求:计算你来到了这个世界多少天
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Scanner; public class Test { public static void main(String[] args) throws ParseException { Scanner sc = new Scanner(System.in); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日"); System.out.println("请输入生日(格式:yyyy年MM月dd日)"); String pattern = sc.next(); Date birthday = simpleDateFormat.parse(pattern); long birthdaydate = birthday.getTime(); Date now = new Date(); long nowdate = now.getTime(); System.out.println("你活了" + (nowdate - birthdaydate) / 1000 / 60 / 60 / 24 + "天"); } } //运行结果: /* 输入:2003年11月3日 输出:你活了7096天 */
3.Calendar类使用
- 创建对象:Calendar是一个抽象类,不能直接创建对象
方法名 | 说明 |
---|---|
public static Calender getInstance() | 获取当前时间的日历对象 |
Calendar类常用方法
方法名 | 说明 |
---|---|
public int get(int field) | 取日历中的某个字段信息 |
public void set(int field,int value) | 修改日历的某个字段信息 |
public void add(int field,int amount) | 为某个字段增加/减少指定的值 |
Calendar:代表的是系统此刻时间对应的日历,通过它可以单独获取、修改时间中的年、月、日、时、分、秒等
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
public class Test {
public static void main(String[] args)
{
Calendar c = Calendar.getInstance();
int i = c.get(Calendar.YEAR);
System.out.println(i);
int month = c.get((Calendar.MONTH));
System.out.println(month + 1);
int day = c.get(Calendar.DAY_OF_MONTH);
System.out.println(day);
char[] weeks = {' ','日','一','二','三','四','五','六'};
//0 1 2 3 4 5 6 7
int weekIndex = c.get(Calendar.DAY_OF_WEEK);
System.out.println(weeks[weekIndex]);
int dayofyear = c.get(Calendar.DAY_OF_YEAR);
System.out.println(dayofyear);
}
}
get方法的参数:Calendar类中的静态常量
- Calendar.YEAR :获取年份信息
- Calendar.MONTH:月份是0~11,记得做+1操作
- Calendar.DAY_OF_MONTH:获取日
- Calendar.DAY_OF_WEEK:获取星期,获取星期的时候,需要提前设计一个数组
- Calendar.DAY_OF_YEAR:获取一年中的第几天
案例:判断2050年3月1日是否是疯狂星期四
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
public class Test {
public static void main(String[] args)
{
Calendar c = Calendar.getInstance();
c.set(2050,3,1);
char[] weeks = {' ','日','一','二','三','四','五','六'};
if(weeks[c.get(Calendar.DAY_OF_WEEK)] == '四')
{
System.out.println("疯狂星期四,V我50");
}
else
{
System.out.println("今天不是疯狂星期四");
}
}
}
//运行结果:
/*
今天不是疯狂星期四
*/
二、JDK8(+)时间类
JDK8(-)传统的时间API缺点
- 设计欠妥,使用不方便,很多都被淘汰了
- 都是可变对象,修改后会丢失最开始的时间信息
- 线程不安全
- 只能精确到毫秒
JDK8(+)新增的时间API
- 设计更合理,功能丰富,使用更方便
- 都是不可变对象,修改后会返回新的时间对象,不会丢失最开始的时间
- 线程安全
- 能精确到毫秒、纳秒
1.日历类
LocalDate:代表本地日期(年、月、日、星期)
LocalTime:代表本地时间(时、分、秒、纳秒)
LocalDateTime:代表本地日期、时间(年、月、日、星期、时、分、秒、纳秒)
获取对象
对象创建方式:
1.now():当前时间
2.of(…):设置时间
LocalDateTime 转换 LocalDate,LocalTime
1.toLocalDate();
2.toLocalTime();
import java.time.LocalDateTime;
public class Test {
public static void main(String[] args)
{
LocalDateTime now = LocalDateTime.now();
System.out.println(now);
System.out.println(now.getYear() + "年");
System.out.println(now.getMonth() + "月");
System.out.println(now.getMonthValue() + "月");
System.out.println(now.getDayOfMonth() + "日");
System.out.println(now.getHour() + "时");
System.out.println(now.getMinute() + "分");
System.out.println(now.getSecond() + "秒");
System.out.println(now.getNano() + "纳秒");
//获取指定的时间对象
LocalDateTime of = LocalDateTime.of(2003,11,3,6,00);
System.out.println(of);
}
}
//运行结果
/*
2023-04-08T13:11:05.934980400
2023年
APRIL月
4月
8日
13时
11分
5秒
934980400纳秒
2003-11-03T06:00
*/
获取年月日时分秒相关的方法
修改年月日时分秒相关的方法
- LocalDateTime、LocalTime、LocalDate都是不可变的,下列方法返回的是一个新的对象
import java.time.LocalDate;
import java.time.LocalDateTime;
public class Test {
public static void main(String[] args)
{
LocalDateTime nowTime = LocalDateTime.now();
//当前时间
System.out.println(nowTime);
//minus:减去
System.out.println("减一小时:" + nowTime.minusHours(1));
System.out.println("减一分钟:" + nowTime.minusMinutes(1));
System.out.println("减一秒钟:" + nowTime.minusSeconds(1));
System.out.println("减一纳秒:" + nowTime.minusNanos(1));
System.out.println("对比时间,确定方法返回的都是新的实例>>>>>>" + nowTime);
System.out.println("-------------------------------------------------------");
//puls:加
System.out.println("加一小时" + nowTime.plusHours(1));
System.out.println("加一分钟" + nowTime.plusMinutes(1));
System.out.println("加一秒钟" + nowTime.plusSeconds(1));
System.out.println("加一纳秒" + nowTime.plusNanos(1));
System.out.println("-------------------------------------------------------");
//with:这里体现出的是,设置效果
System.out.println("修改的效果");
System.out.println(nowTime.withYear(2008));
System.out.println(nowTime.withMonth(8));
System.out.println(nowTime.withDayOfMonth(8));
System.out.println(nowTime.withHour(8));
System.out.println(nowTime.withMonth(8));
System.out.println(nowTime.withSecond(8));
System.out.println(nowTime.withNano(8));
System.out.println("-------------------------------------------------------");
LocalDate myDate = LocalDate.of(2003,11,3);
LocalDate nowDate = LocalDate.now();
//2008-08-08是否在nowDate之前
System.out.println(myDate + "是否在" + nowDate + "之前?" + myDate.isBefore(nowDate));
//2008-08-08是否在nowDate之后
System.out.println(myDate + "是否在" + nowDate + "之后?" + myDate.isAfter(nowDate));
//判断两个时间是否相同
System.out.println(myDate.equals(nowDate));
}
//运行结果:
/*
减一小时:2023-04-08T13:00:51.738803500
减一分钟:2023-04-08T13:59:51.738803500
减一秒钟:2023-04-08T14:00:50.738803500
减一纳秒:2023-04-08T14:00:51.738803499
对比时间,确定方法返回的都是新的实例>>>>>>2023-04-08T14:00:51.738803500
---------------------------------------------------------------
加一小时2023-04-08T15:00:51.738803500
加一分钟2023-04-08T14:01:51.738803500
加一秒钟2023-04-08T14:00:52.738803500
加一纳秒2023-04-08T14:00:51.738803501
---------------------------------------------------------------
修改的效果
2008-04-08T14:00:51.738803500
2023-08-08T14:00:51.738803500
2023-04-08T14:00:51.738803500
2023-04-08T08:00:51.738803500
2023-08-08T14:00:51.738803500
2023-04-08T14:00:08.738803500
2023-04-08T14:00:51.000000008
---------------------------------------------------------------
2003-11-03是否在2023-04-08之前?true
2003-11-03是否在2023-04-08之后?false
false
*/
2.日期格式化类
DateTimeFormatter类
-
用于时间的格式化和解析
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Test {
public static void main(String[] args)
{
LocalDateTime now = LocalDateTime.now();
System.out.println("格式化之前" + now);
//获取格式化对象
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年M月d日");
//格式化
String result = formatter.format(now);
System.out.println("格式化之后" + result);
//解析
String time = "2008年08月08日";
LocalDate parse = LocalDate.parse(time,formatter);
System.out.println(parse);
}
}
//运行结果:
/*
格式化之前2023-04-08T14:06:51.422351100
格式化之后2023年4月8日
2008-08-08
*/
3.时间类
-
Instant类:用于表示时间的对象,类似之前所学习的Date
import java.time.*; public class Test { public static void main(String[] args) { Instant now = Instant.now(); System.out.println("当时的时间截是:" + now); ZonedDateTime zonedDateTime = Instant.now().atZone(ZoneId.of("Asia/Shanghai")); System.out.println(zonedDateTime); } }
-
ZoneId类
import java.time.*; import java.util.Set; public class Test { public static void main(String[] args) { //获取Java中支持的所有时区 Set<String> set = ZoneId.getAvailableZoneIds(); System.out.println(set); System.out.println(set.size()); System.out.println("-----------------------------------------"); //获取系统默认时区 ZoneId zoneId = ZoneId.systemDefault(); System.out.println(zoneId); System.out.println("-----------------------------------------"); //获取一个指定时区 ZoneId of = ZoneId.of("Africa/Nairobi"); System.out.println(of); ZonedDateTime zonedDateTime = Instant.now().atZone(of); System.out.println(zonedDateTime); } } //运行结果: /* [Asia/Aden, America/Cuiaba, Etc/GMT+9, Etc/GMT+8, Africa/Nairobi, America/Marigot, Asia/Aqtau, Pacific/Kwajalein, America/El_Salvador, Asia/Pontianak, Africa/Cairo, Pacific/Pago_Pago, Africa/Mbabane, Asia/Kuching, Pacific/Honolulu, Pacific/Rarotonga, America/Guatemala, Australia/Hobart, Europe/London, America/Belize, America/Panama, Asia/Chungking, America/Managua, America/Indiana/Petersburg, Asia/Yerevan, Europe/Brussels, GMT, Europe/Warsaw, America/Chicago, Asia/Kashgar, Chile/Continental, Pacific/Yap, CET, Etc/GMT-1, Etc/GMT-0, Europe/Jersey, America/Tegucigalpa, Etc/GMT-5, Europe/Istanbul, America/Eirunepe, Etc/GMT-4, America/Miquelon, Etc/GMT-3, Europe/Luxembourg, Etc/GMT-2, Etc/GMT-9, America/Argentina/Catamarca, Etc/GMT-8, Etc/GMT-7, Etc/GMT-6, Europe/Zaporozhye, Canada/Yukon, Canada/Atlantic, Atlantic/St_Helena, Australia/Tasmania, Libya, Europe/Guernsey, America/Grand_Turk, Asia/Samarkand, America/Argentina/Cordoba, Asia/Phnom_Penh, Africa/Kigali, Asia/Almaty, US/Alaska, Asia/Dubai, Europe/Isle_of_Man, America/Araguaina, Cuba, Asia/Novosibirsk, America/Argentina/Salta, Etc/GMT+3, Africa/Tunis, Etc/GMT+2, Etc/GMT+1, Pacific/Fakaofo, Africa/Tripoli, Etc/GMT+0, Israel, Africa/Banjul, Etc/GMT+7, Indian/Comoro, Etc/GMT+6, Etc/GMT+5, Etc/GMT+4, Pacific/Port_Moresby, US/Arizona, Antarctica/Syowa, Indian/Reunion, Pacific/Palau, Europe/Kaliningrad, America/Montevideo, Africa/Windhoek, Asia/Karachi, Africa/Mogadishu, Australia/Perth, Brazil/East, Etc/GMT, Asia/Chita, Pacific/Easter, Antarctica/Davis, Antarctica/McMurdo, Asia/Macao, America/Manaus, Africa/Freetown, Europe/Bucharest, Asia/Tomsk, America/Argentina/Mendoza, Asia/Macau, Europe/Malta, Mexico/BajaSur, Pacific/Tahiti, Africa/Asmera, Europe/Busingen, America/Argentina/Rio_Gallegos, Africa/Malabo, Europe/Skopje, America/Catamarca, America/Godthab, Europe/Sarajevo, Australia/ACT, GB-Eire, Africa/Lagos, America/Cordoba, Europe/Rome, Asia/Dacca, Indian/Mauritius, Pacific/Samoa, America/Regina, America/Fort_Wayne, America/Dawson_Creek, Africa/Algiers, Europe/Mariehamn, America/St_Johns, America/St_Thomas, Europe/Zurich, America/Anguilla, Asia/Dili, America/Denver, Africa/Bamako, Europe/Saratov, GB, Mexico/General, Pacific/Wallis, Europe/Gibraltar, Africa/Conakry, Africa/Lubumbashi, Asia/Istanbul, America/Havana, NZ-CHAT, Asia/Choibalsan, America/Porto_Acre, Asia/Omsk, Europe/Vaduz, US/Michigan, Asia/Dhaka, America/Barbados, Europe/Tiraspol, Atlantic/Cape_Verde, Asia/Yekaterinburg, America/Louisville, Pacific/Johnston, Pacific/Chatham, Europe/Ljubljana, America/Sao_Paulo, Asia/Jayapura, America/Curacao, Asia/Dushanbe, America/Guyana, America/Guayaquil, America/Martinique, Portugal, Europe/Berlin, Europe/Moscow, Europe/Chisinau, America/Puerto_Rico, America/Rankin_Inlet, Pacific/Ponape, Europe/Stockholm, Europe/Budapest, America/Argentina/Jujuy, Australia/Eucla, Asia/Shanghai, Universal, Europe/Zagreb, America/Port_of_Spain, Europe/Helsinki, Asia/Beirut, Asia/Tel_Aviv, Pacific/Bougainville, US/Central, Africa/Sao_Tome, Indian/Chagos, America/Cayenne, Asia/Yakutsk, Pacific/Galapagos, Australia/North, Europe/Paris, Africa/Ndjamena, Pacific/Fiji, America/Rainy_River, Indian/Maldives, Australia/Yancowinna, SystemV/AST4, Asia/Oral, America/Yellowknife, Pacific/Enderbury, America/Juneau, Australia/Victoria, America/Indiana/Vevay, Asia/Tashkent, Asia/Jakarta, Africa/Ceuta, Asia/Barnaul, America/Recife, America/Buenos_Aires, America/Noronha, America/Swift_Current, Australia/Adelaide, America/Metlakatla, Africa/Djibouti, America/Paramaribo, Asia/Qostanay, Europe/Simferopol, Europe/Sofia, Africa/Nouakchott, Europe/Prague, America/Indiana/Vincennes, Antarctica/Mawson, America/Kralendijk, Antarctica/Troll, Europe/Samara, Indian/Christmas, America/Antigua, Pacific/Gambier, America/Indianapolis, America/Inuvik, America/Iqaluit, Pacific/Funafuti, UTC, Antarctica/Macquarie, Canada/Pacific, America/Moncton, Africa/Gaborone, Pacific/Chuuk, Asia/Pyongyang, America/St_Vincent, Asia/Gaza, Etc/Universal, PST8PDT, Atlantic/Faeroe, Asia/Qyzylorda, Canada/Newfoundland, America/Kentucky/Louisville, America/Yakutat, Asia/Ho_Chi_Minh, Antarctica/Casey, Europe/Copenhagen, Africa/Asmara, Atlantic/Azores, Europe/Vienna, ROK, Pacific/Pitcairn, America/Mazatlan, Australia/Queensland, Pacific/Nauru, Europe/Tirane, Asia/Kolkata, SystemV/MST7, Australia/Canberra, MET, Australia/Broken_Hill, Europe/Riga, America/Dominica, Africa/Abidjan, America/Mendoza, America/Santarem, Kwajalein, America/Asuncion, Asia/Ulan_Bator, NZ, America/Boise, Australia/Currie, EST5EDT, Pacific/Guam, Pacific/Wake, Atlantic/Bermuda, America/Costa_Rica, America/Dawson, Asia/Chongqing, Eire, Europe/Amsterdam, America/Indiana/Knox, America/North_Dakota/Beulah, Africa/Accra, Atlantic/Faroe, Mexico/BajaNorte, America/Maceio, Etc/UCT, Pacific/Apia, GMT0, America/Atka, Pacific/Niue, Australia/Lord_Howe, Europe/Dublin, Pacific/Truk, MST7MDT, America/Monterrey, America/Nassau, America/Jamaica, Asia/Bishkek, America/Atikokan, Atlantic/Stanley, Australia/NSW, US/Hawaii, SystemV/CST6, Indian/Mahe, Asia/Aqtobe, America/Sitka, Asia/Vladivostok, Africa/Libreville, Africa/Maputo, Zulu, America/Kentucky/Monticello, Africa/El_Aaiun, Africa/Ouagadougou, America/Coral_Harbour, Pacific/Marquesas, Brazil/West, America/Aruba, America/North_Dakota/Center, America/Cayman, Asia/Ulaanbaatar, Asia/Baghdad, Europe/San_Marino, America/Indiana/Tell_City, America/Tijuana, Pacific/Saipan, SystemV/YST9, Africa/Douala, America/Chihuahua, America/Ojinaga, Asia/Hovd, America/Anchorage, Chile/EasterIsland, America/Halifax, Antarctica/Rothera, America/Indiana/Indianapolis, US/Mountain, Asia/Damascus, America/Argentina/San_Luis, America/Santiago, Asia/Baku, America/Argentina/Ushuaia, Atlantic/Reykjavik, Africa/Brazzaville, Africa/Porto-Novo, America/La_Paz, Antarctica/DumontDUrville, Asia/Taipei, Antarctica/South_Pole, Asia/Manila, Asia/Bangkok, Africa/Dar_es_Salaam, Poland, Atlantic/Madeira, Antarctica/Palmer, America/Thunder_Bay, Africa/Addis_Ababa, Asia/Yangon, Europe/Uzhgorod, Brazil/DeNoronha, Asia/Ashkhabad, Etc/Zulu, America/Indiana/Marengo, America/Creston, America/Punta_Arenas, America/Mexico_City, Antarctica/Vostok, Asia/Jerusalem, Europe/Andorra, US/Samoa, PRC, Asia/Vientiane, Pacific/Kiritimati, America/Matamoros, America/Blanc-Sablon, Asia/Riyadh, Iceland, Pacific/Pohnpei, Asia/Ujung_Pandang, Atlantic/South_Georgia, Europe/Lisbon, Asia/Harbin, Europe/Oslo, Asia/Novokuznetsk, CST6CDT, Atlantic/Canary, America/Knox_IN, Asia/Kuwait, SystemV/HST10, Pacific/Efate, Africa/Lome, America/Bogota, America/Menominee, America/Adak, Pacific/Norfolk, Europe/Kirov, America/Resolute, Pacific/Kanton, Pacific/Tarawa, Africa/Kampala, Asia/Krasnoyarsk, Greenwich, SystemV/EST5, America/Edmonton, Europe/Podgorica, Australia/South, Canada/Central, Africa/Bujumbura, America/Santo_Domingo, US/Eastern, Europe/Minsk, Pacific/Auckland, Africa/Casablanca, America/Glace_Bay, Canada/Eastern, Asia/Qatar, Europe/Kiev, Singapore, Asia/Magadan, SystemV/PST8, America/Port-au-Prince, Europe/Belfast, America/St_Barthelemy, Asia/Ashgabat, Africa/Luanda, America/Nipigon, Atlantic/Jan_Mayen, Brazil/Acre, Asia/Muscat, Asia/Bahrain, Europe/Vilnius, America/Fortaleza, Etc/GMT0, US/East-Indiana, America/Hermosillo, America/Cancun, Africa/Maseru, Pacific/Kosrae, Africa/Kinshasa, Asia/Kathmandu, Asia/Seoul, Australia/Sydney, America/Lima, Australia/LHI, America/St_Lucia, Europe/Madrid, America/Bahia_Banderas, America/Montserrat, Asia/Brunei, America/Santa_Isabel, Canada/Mountain, America/Cambridge_Bay, Asia/Colombo, Australia/West, Indian/Antananarivo, Australia/Brisbane, Indian/Mayotte, US/Indiana-Starke, Asia/Urumqi, US/Aleutian, Europe/Volgograd, America/Lower_Princes, America/Vancouver, Africa/Blantyre, America/Rio_Branco, America/Danmarkshavn, America/Detroit, America/Thule, Africa/Lusaka, Asia/Hong_Kong, Iran, America/Argentina/La_Rioja, Africa/Dakar, SystemV/CST6CDT, America/Tortola, America/Porto_Velho, Asia/Sakhalin, Etc/GMT+10, America/Scoresbysund, Asia/Kamchatka, Asia/Thimbu, Africa/Harare, Etc/GMT+12, Etc/GMT+11, Navajo, America/Nome, Europe/Tallinn, Turkey, Africa/Khartoum, Africa/Johannesburg, Africa/Bangui, Europe/Belgrade, Jamaica, Africa/Bissau, Asia/Tehran, WET, Europe/Astrakhan, Africa/Juba, America/Campo_Grande, America/Belem, Etc/Greenwich, Asia/Saigon, America/Ensenada, Pacific/Midway, America/Jujuy, Africa/Timbuktu, America/Bahia, America/Goose_Bay, America/Virgin, America/Pangnirtung, Asia/Katmandu, America/Phoenix, Africa/Niamey, America/Whitehorse, Pacific/Noumea, Asia/Tbilisi, Europe/Kyiv, America/Montreal, Asia/Makassar, America/Argentina/San_Juan, Hongkong, UCT, Asia/Nicosia, America/Indiana/Winamac, SystemV/MST7MDT, America/Argentina/ComodRivadavia, America/Boa_Vista, America/Grenada, Asia/Atyrau, Australia/Darwin, Asia/Khandyga, Asia/Kuala_Lumpur, Asia/Famagusta, Asia/Thimphu, Asia/Rangoon, Europe/Bratislava, Asia/Calcutta, America/Argentina/Tucuman, Asia/Kabul, Indian/Cocos, Japan, Pacific/Tongatapu, America/New_York, Etc/GMT-12, Etc/GMT-11, America/Nuuk, Etc/GMT-10, SystemV/YST9YDT, Europe/Ulyanovsk, Etc/GMT-14, Etc/GMT-13, W-SU, America/Merida, EET, America/Rosario, Canada/Saskatchewan, America/St_Kitts, Arctic/Longyearbyen, America/Fort_Nelson, America/Caracas, America/Guadeloupe, Asia/Hebron, Indian/Kerguelen, SystemV/PST8PDT, Africa/Monrovia, Asia/Ust-Nera, Egypt, Asia/Srednekolymsk, America/North_Dakota/New_Salem, Asia/Anadyr, Australia/Melbourne, Asia/Irkutsk, America/Shiprock, America/Winnipeg, Europe/Vatican, Asia/Amman, Etc/UTC, SystemV/AST4ADT, Asia/Tokyo, America/Toronto, Asia/Singapore, Australia/Lindeman, America/Los_Angeles, SystemV/EST5EDT, Pacific/Majuro, America/Argentina/Buenos_Aires, Europe/Nicosia, Pacific/Guadalcanal, Europe/Athens, US/Pacific, Europe/Monaco] 602 ----------------------------------------- Asia/Shanghai ----------------------------------------- Africa/Nairobi 2023-04-08T09:17:21.363776200+03:00[Africa/Nairobi] */
-
Instant时间戳
用于表现时间的对象,类似之前所学习的Date
import java.time.*; import java.util.Set; public class Test { public static void main(String[] args) { //获取当前时间的Instant对象(标准时间) Instant now = Instant.now(); System.out.println("当前时间为(世界标准时间):" + now); System.out.println("----------------------------------"); //根据(秒/毫秒/纳秒)获取Instant对象 Instant instant1 = Instant.ofEpochMilli(1000); Instant instant2 = Instant.ofEpochSecond(5); System.out.println(instant1); System.out.println(instant2); System.out.println("----------------------------------"); //指定时区 ZonedDateTime zonedDateTime = Instant.now().atZone(ZoneId.systemDefault()); System.out.println("带时间的时区:" + zonedDateTime); System.out.println("----------------------------------"); //判断系列的方法 System.out.println(now.isBefore(instant1)); System.out.println(now.isAfter(instant1)); System.out.println("----------------------------------"); //减少时间系列的方法 System.out.println("减1000毫秒:" + now.minusMillis(1000)); System.out.println("减1000毫秒:" + now.minusSeconds(5)); System.out.println("----------------------------------"); //增加时间系列的方法 System.out.println("加1000毫秒:" + now.plusMillis(1000)); System.out.println("加5秒钟:" + now.plusSeconds(5)); System.out.println("----------------------------------"); } } //运行结果: /* ---------------------------------- 1970-01-01T00:00:01Z 1970-01-01T00:00:05Z ---------------------------------- 带时间的时区:2023-04-08T14:27:00.841167600+08:00[Asia/Shanghai] ---------------------------------- false true ---------------------------------- 减1000毫秒:2023-04-08T06:26:59.836179900Z 减1000毫秒:2023-04-08T06:26:55.836179900Z ---------------------------------- 加1000毫秒:2023-04-08T06:27:01.836179900Z 加5秒钟:2023-04-08T06:27:05.836179900Z ---------------------------------- */
-
ZoneDateTime带时区的时间对象
import java.time.*; import java.util.Set; public class Test { public static void main(String[] args) { //获取当前时间的ZoneDateTime对象 ZonedDateTime now = ZonedDateTime.now(); System.out.println(now); System.out.println("---------------------------------------------"); //获取指定时间的ZoneDateTime对象 ZonedDateTime of = ZonedDateTime.of (2008,8,8,8,8,8,8,ZoneId.systemDefault()); System.out.println(of); System.out.println("---------------------------------------------"); //修改时间系列的方法 System.out.println(now.withYear(2008)); System.out.println(now.withMonth(8)); System.out.println(now.withDayOfMonth(8)); System.out.println("---------------------------------------------"); //减少时间系列的方法 System.out.println(now.minusYears(1)); System.out.println(now.minusMonths(1)); System.out.println(now.minusDays(1)); System.out.println("---------------------------------------------"); //增加时间系列的方法 System.out.println(now.plusYears(1)); System.out.println(now.plusMonths(1)); System.out.println(now.plusDays(1)); } } //运行结果: /* 2023-04-08T14:33:49.214969800+08:00[Asia/Shanghai] --------------------------------------------- 2008-08-08T08:08:08.000000008+08:00[Asia/Shanghai] --------------------------------------------- 2008-04-08T14:33:49.214969800+08:00[Asia/Shanghai] 2023-08-08T14:33:49.214969800+08:00[Asia/Shanghai] 2023-04-08T14:33:49.214969800+08:00[Asia/Shanghai] --------------------------------------------- 2022-04-08T14:33:49.214969800+08:00[Asia/Shanghai] 2023-03-08T14:33:49.214969800+08:00[Asia/Shanghai] 2023-04-07T14:33:49.214969800+08:00[Asia/Shanghai] --------------------------------------------- 2024-04-08T14:33:49.214969800+08:00[Asia/Shanghai] 2023-05-08T14:33:49.214969800+08:00[Asia/Shanghai] 2023-04-09T14:33:49.214969800+08:00[Asia/Shanghai] */
4.工具类
-
Period类(年月日)
import java.time.*; import java.util.Set; public class Test { public static void main(String[] args) { //此刻年月日 LocalDate today = LocalDate.now(); System.out.println(today); //昨天年月日 LocalDate otherDate = LocalDate.of(2023,4,7); System.out.println(otherDate); //Period对象表示时间的间隔对象 Period period = Period.between(today,otherDate); System.out.println(period.getYears()); System.out.println(period.getMonths()); System.out.println(period.getDays()); System.out.println(period.toTotalMonths()); } } //运行结果 /* 2023-04-08 2023-04-07 0 0 -1 0 */
-
Duration类
计算日期分隔(时分秒)
import java.time.*; import java.util.Set; public class Test { public static void main(String[] args) { //此刻年月日 LocalDateTime today = LocalDateTime.now(); System.out.println(today); //昨天年月日 LocalDateTime otherDate = LocalDateTime.of(2023,4,7,0,0,0); System.out.println(otherDate); //Period对象表示时间的间隔对象 Duration duration = Duration.between(otherDate,today);//第二个参数减第一个参数 System.out.println(duration.toDays()); System.out.println(duration.toHours()); System.out.println(duration.toMinutes()); System.out.println(duration.toMillis()); System.out.println(duration.toNanos()); } } //运行结果 /* 2023-04-08T14:41:51.591002 2023-04-07T00:00 1 38 2321 139311591 139311591002000 */
-
ChronoUnit可用于在单个时间内测量一段时间,这个工具类是最全了的,可以用于比较所有的时间单位
import java.time.*; import java.time.temporal.ChronoUnit; import java.util.Set; public class Test { public static void main(String[] args) { //本地日期时间对象:此刻的 LocalDateTime today = LocalDateTime.now(); System.out.println(today); //生日时间 LocalDateTime birthDate = LocalDateTime.of (2003,11,3,0,0,0); System.out.println(birthDate); System.out.println("相差的年数:" + ChronoUnit.YEARS.between(birthDate,today)); System.out.println("相差的月数:" + ChronoUnit.MONTHS.between(birthDate,today)); System.out.println("相差的周数:" + ChronoUnit.WEEKS.between(birthDate,today)); System.out.println("相差的天数:" + ChronoUnit.DAYS.between(birthDate,today)); System.out.println("相差的时数:" + ChronoUnit.HOURS.between(birthDate,today)); System.out.println("相差的分数:" + ChronoUnit.MINUTES.between(birthDate,today)); System.out.println("相差的秒数:" + ChronoUnit.SECONDS.between(birthDate,today)); System.out.println("相差的毫秒数:" + ChronoUnit.MILLIS.between(birthDate,today)); System.out.println("相差的微秒数:" + ChronoUnit.MICROS.between(birthDate,today)); System.out.println("相差的纳秒数:" + ChronoUnit.NANOS.between(birthDate,today)); System.out.println("相差的半天数:" + ChronoUnit.HALF_DAYS.between(birthDate,today)); System.out.println("相差的十年数:" + ChronoUnit.DECADES.between(birthDate,today)); System.out.println("相差的世纪(百年)数:" + ChronoUnit.CENTURIES.between(birthDate,today)); System.out.println("相差的千年数:" + ChronoUnit.MILLENNIA.between(birthDate,today)); System.out.println("相差的纪元数:" + ChronoUnit.ERAS.between(birthDate,today)); } } //运行结果 /* 2023-04-08T14:48:31.251359900 2003-11-03T00:00 相差的年数:19 相差的月数:233 相差的周数:1013 相差的天数:7096 相差的时数:170318 相差的分数:10219128 相差的秒数:613147711 相差的毫秒数:613147711251 相差的微秒数:613147711251359 相差的纳秒数:613147711251359900 相差的半天数:14193 相差的十年数:1 相差的世纪(百年)数:0 相差的千年数:0 相差的纪元数:0 */