关于时间

全网最全!彻底弄透Java处理GMT/UTC日期时间

image.png

概念

  • HTTP日期时间。所有HTTP日期/时间戳都必须用格林威治标准时间(GMT)表示,没有例外。对于HTTP来说,GMT完全等于UTC(协调世界时)。
  • UTC和GMT的联系。UTC是标准时间参照,像GMT(格林威治时间)、ET(美国东部时间)、PST(太平洋时间)、CST(北京时间)等等都是具体的时区时间。GMT能和UTC直接转换,仅仅是因为碰巧GMT是0时区时间,数值上刚好和UTC是相等的(不需要精确到秒的情况下,二者可以视为相等)。
  • UTC偏移量。常见的表示形式有:±[hh]:[mm]、±[hh][mm]、±[hh]这三种方式均可。
  • 默认时区。很多公司在阿里云、腾讯云、国内外的云主机上部署应用时,全部都是采用运维设置统一时区:中国时区,这种方式来管理的。
  • 自己平时开发中前端就是扔个字符串给我,然后我就给格式化为一个Date类型,并没有传入时区参数?这是因为默认情况下你们交互双发就达成了契约:双方均使用的是北京时间(时区),既然是相同时区,所以互通有无不会有任何问题。不信你把你接口给海外用户调试试?
  • ZoneId和ZoneOffset.。若你使用ZoneId时区去表示就很方便喽,比如纽约是西五区,你在任何时候获取其当地时间都是能得到正确答案的,因为它内置了对夏令时规则的处理,也就是说啥时候+1啥时候-1时区自己门清,不需要API调用者关心。没有夏令时问题。ZoneId只是一个用于获取底层规则的ID。之所以采用这种方法,是因为规则是由政府定义的,并且经常变化,而ID是稳定的。
  • 根据偏移量得到的ZoneId内部并无现成时区规则可用,因此对于有夏令营的国家转换可能出问题,一般不建议这么去做。
  • ZoneId并没有提供设置默认时区的方法,设置默认时区方式完全遵照TimeZone的方式即可。
  • 夏令时是为节约能源而人为规定地方时间的制度(鼓励人们早睡早起,不要浪费电,夏天日照时间长尽量多用自然资源)。在夏令时开始这天将时钟往前拨拨1个小时,11.1号这天还原回来。(时区+1,相对非夏令时提早干活)。比如夏令时期间带时区解析后的结果:字符串参数偏移量明明是-05,转换为ZonedDateTime后偏移量成为了-04。

image.png

  • OffsetDateTime和Instant可用于模型的字段类型,因为它们都表示瞬间值并且还不可变,所以适合网络传输或者数据库持久化。ZonedDateTime不适合网络传输/持久化,因为即使同一个ZoneId时区,不同地方获取到瞬时值也有可能不一样。
  • ZonedDateTime可简单认为是LocalDateTime和ZoneId的组合。而ZoneOffset是其内置的动态计算出来的一个次要信息,以确保输出一个瞬时值而存在,毕竟在某个瞬间偏移量ZoneOffset肯定是确定的。
  • OffsetDateTime无法支持夏令时等规则,但ZonedDateTime可以很好的处理夏令时调整。OffsetDateTime代表一个瞬时值,而ZonedDateTime的值是不稳定的,需要在某个瞬时根据当时的规则计算出来偏移量从而确定实际值。总的来说,OffsetDateTime和ZonedDateTime的区别主要在于ZoneOffset和ZoneId的区别。如果你只是用来传递数据,请使用OffsetDateTime,若你想在特定时区里做时间显示那么请务必使用ZonedDateTime。
类型名 格式 说明
ISO 8601 一般:2020-12-05T05:33:19Z
东八:2004-05-03T17:30:08+08:00
z表示偏移量=0
国际标准化组织的日期和时间的表示方法,这种格式是最常用的格式。
RFC2822 1992/02/12 12:23:22+0800 符合rfc2822格式的时间
格林威治标准时间GMT Mon, 29 Apr 2019 09:52:21 GMT 格林威治的子午线作为划分地球东西两半球的经度零度,并作为时间的零点
世界协调时间UTC Mon, 29 Apr 2019 09:52:21 经过平均太阳时(以格林威治时间GMT为准)、地轴运动修正后的新时标以及以「秒」为单位的国际原子时所综合精算而成的时间,计算过程相当严谨精密
Unix时间戳 以秒为单位:1607150827 以纳秒为单位:1607150827857990329 是一种时间表示方式,定义为从格林威治时间1970年01月01日00时00分00秒起至现在的总秒数。

日期/时间模式

字母 含义 匹配类型 示例
y Year 2020,20
M Month July; Jul; 07
d 月中的天数(俗称日,最大值31) Number 10
H 小时(0-23) Number 0,23
m 分钟(0-59) Number 30,59
s 秒(0-59) Number 30,59
—- —- —- yyyy-MM-dd HH:mm:ss(分隔符可以是任意字符,甚至汉字)
Y 当前周所在的年份 Year 2020(不建议使用,周若跨年有坑)
S 毫秒数(1-999) Number 999
a am/pm Text PM
z 时区 通用时区 Pacific Standard Time; PST; GMT-08:00
Z 时区 RFC 822时区 -0800,+0800
X 时区 ISO 8601时区 -08; -0800; -08:00
G 年代 Text AD(公元)、BC(公元前)
D 年中的天数(1-366) Number 360
w 年中的周数(1-54) Number 27
W 月中的周数(1-5) Number 3
E 星期几名称 Text Tuesday; Tue
u 星期几数字(1=Monday…) Number 1
k 小时(1-24) Number 不建议使用
K/h am/pm小时数字 Number 一般配合a一起使用

jdk8 LocalDate等

image.png
参考:Java8新特性日期API by 阿牛

  1. new Date(): Sun Jan 02 19:22:20 CST 2022
  2. ============Local===============
  3. LocalDateTime.now(): 2022-01-02T19:22:20.281056
  4. LocalDateTime.of: 2021-01-02T17:23:52
  5. localDate.atTime(localTime): 2021-01-02T17:23:59
  6. getDayOfMonth(): 2
  7. =============Instant========================
  8. System.currentTimeMillis(): 1641122540286
  9. Instant.now(): 2022-01-02T11:22:20.292162Z
  10. Instant.now().toEpochMilli(): 1641122540297
  11. LocalDateTime.now() with systemDefaultZone to toEpochMilli: 1641122540298
  12. Instant.ofEpochSecond(120, 100000): 1970-01-01T00:02:00.000100Z
  13. =============Duration=============
  14. Duration.between: 7
  15. Duration.of Days: 5
  16. Duration.of MILLIS: 1000
  17. =============Period================
  18. Period.of(): 6
  19. Period.between():1
  20. ==========================增加和减少日期===========================================
  21. TemporalAdjusters.nextOrSame: 2022-01-08
  22. TemporalAdjusters.lastInMonth: 2022-01-29
  23. ==========================格式化日期===========================================
  24. format DateTimeFormatter.ISO_DATE_TIME: 2022-01-02T19:22:20.306401
  25. format DateTimeFormatter.ofPattern: 2022-01-02
  26. parse DateTimeFormatter.ofPattern: 2021-01-04T17:39:30
  27. ==========================时区ZoneId===========================================
  28. ZoneId.getAvailableZoneIds()[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/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, 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]
  29. ZoneId.systemDefault(): Asia/Shanghai
  30. ZoneId.of("Asia/Shanghai"): Asia/Shanghai
  31. ========================时区ZonedDateTime, OffsetDateTime===================================
  32. ZonedDateTime.of() Shanghai, 2022-01-02T19:22:20.313885+08:00[Asia/Shanghai]
  33. ZonedDateTime.of() America, 2022-01-02T19:22:20.314281-04:00[America/Cuiaba]
  34. OffsetDateTime.of(), -42022-01-02T19:22:20.315687-04:00
  35. OffsetDateTime.of(), UTC2022-01-02T19:22:20.316207Z
  36. =======================Clock==================================================
  37. System.currentTimeMillis(): 1641122540316
  38. Clock.systemDefaultZone(): SystemClock[Asia/Shanghai]
  39. Clock.systemUTC(): SystemClock[Z]
  40. Clock systemDefaultZone millis: 1641122540317
  41. Clock systemUTC millis: 1641122540317
  42. Clock systemDefaultZone instant: 2022-01-02T11:22:20.317917Z
  43. Clock systemUTC instant: 2022-01-02T11:22:20.318222Z
  44. LocalDateTime.now with Clock.systemDefaultZone()2022-01-02T19:22:20.318516
  45. LocalDateTime.now with Clock.systemUTC()2022-01-02T11:22:20.318801
  46. LocalDateTime.now with zoneId default: 2022-01-02T19:22:20.319114
  47. LocalDateTime.now with zoneId of: 2022-01-02T07:22:20.319415

LocalDate等新增类

Instant代替 Date,LocalDateTime代替 Calendar,DateTimeFormatter 代替 SimpleDateFormat。

  • LocalDate
  • LocalTime
  • LocalDateTime

它们定义了一个没有时区信息的时间,默认是本地运行所在时区的时间,通过使用atZone、Clock参数等方式可得到相应时区的时间。

  • Instant

Instant用于表示一个时间戳,相对于UTC时间
toInstant()方法会进行转换:The calculation combines the local date-time and offset.

  • Duration
  • Period:Period在概念上和Duration类似,区别在于Period是以年月日来衡量一个时间段,比如2年3个月6天
  • Clock

Clock 类提供了访问当前日期和时间的方法,Clock 是时区敏感的。如果你需要对不同时区的日期进行处理的话这是相当方便的,LocalDateTime.now(Clock.system(ZoneId.of("xxx")))

增加和减少日期

  • with()plus
  • TemporalAdjuster接口

    1. // 如果TemporalAdjusters类的方法不能满足使用,可以创建自定义的TemporalAdjuster接口的实现
    2. @FunctionalInterface
    3. public interface TemporalAdjuster {
    4. Temporal adjustInto(Temporal temporal);
    5. }
  • TemporalAdjusters类: | 方法名 | 描述 | | —- | —- | | firstInMonth | 返回同一个月中第一个星期几 | | nextOrSame / previousOrSame | 返回后一个/前一个给定的星期几,如果这个值满足条件,直接返回 |

Duration和Period

  • Duration表示一个时间段,所以Duration类中不包含now()静态方法。可以通过Duration.between()方法创建Duration对象。
  • Period在概念上和Duration类似,区别在于Period是以年月日来衡量一个时间段。

    格式化日期DateTimeFormatter

    formatparse
格式化器 示例
ofLocalizedDate(dateStyle) ‘2021-01-03’
ofLocalizedTime(timeStyle) ‘10:15:30’
ofLocalizedDateTime(dateTimeStyle) ‘3 Jun 2021 11:05:30’
ISO_LOCAL_DATE ‘2021-12-03’
ISO_LOCAL_TIME ‘10:15:30’
ISO_LOCAL_DATE_TIME ‘2021-12-03T10:15:30’
ISO_OFFSET_DATE_TIME ‘2021-12-03T10:15:30+01:00’
ISO_ZONED_DATE_TIME ‘2021-12-03T10:15:30+01:00[Europe/Paris]’

时区

ZoneId
ZonedDateTimeOffsetDateTime

Clock应用于单元测试

  1. /**
  2. * Clock.fixed
  3. * Obtains a clock that always returns the same instant.
  4. * This clock simply returns the specified instant. As such, it is not a clock in the conventional sense. The main use case for this is in testing, where the fixed clock ensures tests are not dependent on the current clock.
  5. * The returned implementation is immutable, thread-safe and Serializable.
  6. * Params:
  7. * fixedInstant – the instant to use as the clock, not null
  8. * zone – the time-zone to use to convert the instant to date-time, not null
  9. * Returns:
  10. * a clock that always returns the same instant, not null
  11. * @param localTime
  12. * @return
  13. */
  14. private Clock createFixedClock(LocalTime localTime) {
  15. ZoneId zoneId = ZoneId.systemDefault();
  16. Instant instant = localTime.atDate(LocalDate.now()).atZone(zoneId).toInstant();
  17. return Clock.fixed(instant, zoneId);
  18. }

与Date的相互转换

转换demo
Date -> LocalDateTime

  1. @Test
  2. public void test() {
  3. // 关键步骤:
  4. Instant instant = date.toInstant();
  5. LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
  6. }

LocalDateTime -> Date

  1. @Test
  2. public void test() {
  3. // 关键步骤:
  4. Instant instant = localDateTime.atZone(zone).toInstant();
  5. java.util.Date date = Date.from(instant);
  6. }

案例

  1. // 距离过期还有不到一个月
  2. public boolean hasReminderOfExpireDate() {
  3. LocalDate now = LocalDate.now();
  4. return remain > 0 && expiredDate.isBefore(now.plusDays(31));
  5. }

Date

SimpleDateFormat

  1. new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US)
  2. simpleDateFormat.setTimeZone(TimeZone.getDefault());
  3. simpleDateFormat.format(date);
  4. simpleDateFormat.parse();
  1. String dateString = "2020-02-12 20:55:09";
  2. DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  3. Date date = null;
  4. try {
  5. date = df.parse(dateString);
  6. } catch (ParseException e) {
  7. e.printStackTrace();
  8. }
  1. Date currentTime = new Date();
  2. SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  3. String dateString = formatter.format(currentTime);

Calendar

  1. new GregorianCalendar(2021, Calendar.JUNE, 8).getTime()

TimeZone

  1. TimeZone.getAvailableIDs();
  2. TimeZone.getTimeZone("GMT+08:00").getID();
  3. TimeZone.getTimeZone("America/New_York").getID();
  4. TimeZone.setDefault(TimeZone.getTimeZone("GMT+06:00"));

https://24timezones.com/time-zones