前言
接着源碼閱讀:new Date之旅,補充幾種關於獲取當前時間的方式。
Date
在Java中,獲取當前日期最簡單的方法之一就是直接實例化位於Java包java.util的Date類。
Date date = new Date();
System.currentTimeMillis
獲取標準時間可以通過System.currentTimeMillis()方法獲取,此方法不受時區影響,得到的結果是時間戳格式的。
long time = System.currentTimeMillis();
源碼:
/**
* Returns the current time in milliseconds. Note that
* while the unit of time of the return value is a millisecond,
* the granularity of the value depends on the underlying
* operating system and may be larger. For example, many
* operating systems measure time in units of tens of
* milliseconds.
*
* <p> See the description of the class <code>Date</code> for
* a discussion of slight discrepancies that may arise between
* "computer time" and coordinated universal time (UTC).
*
* @return the difference, measured in milliseconds, between
* the current time and midnight, January 1, 1970 UTC.
* @see java.util.Date
*/
public static native long currentTimeMillis();
Calendar
Calendar類,專門用於轉換特定時刻和日曆字段之間的日期和時間。
Calendar calendar = Calendar.getInstance();
源碼:
/**
* Gets a calendar using the default time zone and locale. The
* <code>Calendar</code> returned is based on the current time
* in the default time zone with the default
* {@link Locale.Category#FORMAT FORMAT} locale.
*
* @return a Calendar.
*/
public static Calendar getInstance()
{
return createCalendar(TimeZone.getDefault(), Locale.getDefault(Locale.Category.FORMAT));
}
private static Calendar createCalendar(TimeZone zone,
Locale aLocale)
{
CalendarProvider provider =
LocaleProviderAdapter.getAdapter(CalendarProvider.class, aLocale)
.getCalendarProvider();
if (provider != null) {
try {
return provider.getInstance(zone, aLocale);
} catch (IllegalArgumentException iae) {
// fall back to the default instantiation
}
}
Calendar cal = null;
if (aLocale.hasExtensions()) {
String caltype = aLocale.getUnicodeLocaleType("ca");
if (caltype != null) {
switch (caltype) {
case "buddhist":
cal = new BuddhistCalendar(zone, aLocale);
break;
case "japanese":
cal = new JapaneseImperialCalendar(zone, aLocale);
break;
case "gregory":
cal = new GregorianCalendar(zone, aLocale);
break;
}
}
}
if (cal == null) {
// If no known calendar type is explicitly specified,
// perform the traditional way to create a Calendar:
// create a BuddhistCalendar for th_TH locale,
// a JapaneseImperialCalendar for ja_JP_JP locale, or
// a GregorianCalendar for any other locales.
// NOTE: The language, country and variant strings are interned.
if (aLocale.getLanguage() == "th" && aLocale.getCountry() == "TH") {
cal = new BuddhistCalendar(zone, aLocale);
} else if (aLocale.getVariant() == "JP" && aLocale.getLanguage() == "ja"
&& aLocale.getCountry() == "JP") {
cal = new JapaneseImperialCalendar(zone, aLocale);
} else {
cal = new GregorianCalendar(zone, aLocale);
}
}
return cal;
}
LocalDateTime
LocalDateTime,是Java中最常用的Date / Time類,代表前兩個類的組合 – 即日期和時間的值。
LocalDateTime dateTime = LocalDateTime.now();
源碼:
/**
* Obtains the current date-time from the system clock in the default time-zone.
* <p>
* This will query the {@link Clock#systemDefaultZone() system clock} in the default
* time-zone to obtain the current date-time.
* <p>
* Using this method will prevent the ability to use an alternate clock for testing
* because the clock is hard-coded.
*
* @return the current date-time using the system clock and default time-zone, not null
*/
public static LocalDateTime now() {
return now(Clock.systemDefaultZone());
}
/**
* Obtains the current date-time from the specified clock.
* <p>
* This will query the specified clock to obtain the current date-time.
* Using this method allows the use of an alternate clock for testing.
* The alternate clock may be introduced using {@link Clock dependency injection}.
*
* @param clock the clock to use, not null
* @return the current date-time, not null
*/
public static LocalDateTime now(Clock clock) {
Objects.requireNonNull(clock, "clock");
final Instant now = clock.instant(); // called once
ZoneOffset offset = clock.getZone().getRules().getOffset(now);
return ofEpochSecond(now.getEpochSecond(), now.getNano(), offset);
}
/**
* Obtains an instance of {@code LocalDateTime} using seconds from the
* epoch of 1970-01-01T00:00:00Z.
* <p>
* This allows the {@link ChronoField#INSTANT_SECONDS epoch-second} field
* to be converted to a local date-time. This is primarily intended for
* low-level conversions rather than general application usage.
*
* @param epochSecond the number of seconds from the epoch of 1970-01-01T00:00:00Z
* @param nanoOfSecond the nanosecond within the second, from 0 to 999,999,999
* @param offset the zone offset, not null
* @return the local date-time, not null
* @throws DateTimeException if the result exceeds the supported range,
* or if the nano-of-second is invalid
*/
public static LocalDateTime ofEpochSecond(long epochSecond, int nanoOfSecond, ZoneOffset offset) {
Objects.requireNonNull(offset, "offset");
NANO_OF_SECOND.checkValidValue(nanoOfSecond);
long localSecond = epochSecond + offset.getTotalSeconds(); // overflow caught later
long localEpochDay = Math.floorDiv(localSecond, SECONDS_PER_DAY);
int secsOfDay = (int)Math.floorMod(localSecond, SECONDS_PER_DAY);
LocalDate date = LocalDate.ofEpochDay(localEpochDay);
LocalTime time = LocalTime.ofNanoOfDay(secsOfDay * NANOS_PER_SECOND + nanoOfSecond);
return new LocalDateTime(date, time);
}
結果
先贊後看,養成習慣。歡迎收看一個行走的熊貓程序猿,下期再見