java当前时间获取
前言
接着源码阅读: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 onceZoneOffset 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 laterlong 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);}
结果
先赞后看,养成习惯。欢迎收看一个行走的熊猫程序猿,下期再见
java当前时间获取相关推荐
- Java中时间获取(传智播客毕老师视频讲解)
1.Date类 Date类中大多方法已经过时,且其打印的时间看不懂,可以调用DateFormat接口中的实现子类SimpleDateFormat进行格式调整: 代码如下: import java.ut ...
- java季度时间获取工具类
1.获取当前季度 第一天或最后一天 /*** 获取季度 第一天或最后一天** @param quarters 0本季度,1下季度,-1上季度 以此类推* @param isFirst true获取开始 ...
- java时间格式化取月份_Java格式化时间获取年月日
Java格式化时间获取年月日 import java.util.Date; class Untitled { public static void main(String[] args) { Date ...
- java里 currenttime_java 获取当前时间LocalDateTime currentTimeMillis java.util.Date
总结java里面关于获取当前时间的一些方法 System.currentTimeMillis() 获取标准时间可以通过System.currentTimeMillis()方法获取,此方法不受时区影响, ...
- java ftp取远程服务器时间_在 Java 中如何获取 FTP 服务器上的文件修改时间
使用 Apache Commons Net 进行 FTP 编程的时候,可以使用 FTPClient 类的方法来获取和设置 FTP 服务器上特定文件的修改时间: String getModificati ...
- Java中时间格式化(获取指定时间)
Java中时间格式化(获取指定时间,七天前) 1.通过获取当前系统时间,格式化后转为"yyyy-MM-dd HH:mm:ss"格式并输出: 2.可获取指定时间,如七天前,一年前等, ...
- Java:如何获取当前时间
本文介绍如何从新的 Java 8 java.time.* 中获取当前日期时间,如 Localdate.LocalTime.LocalDateTime.ZonedDateTime.Instant 以及旧 ...
- java当前时间_java 获取当前时间的三种方法
总结java里面关于获取当前时间的一些方法 System.currentTimeMillis() 获取标准时间可以通过System.currentTimeMillis()方法获取,此方法不受时区影响, ...
- java根据当前时间或指定时间获取前后几天或前后几个月或前后几年的时间
根据当前时间计算 获取前后几天 /*** @Author: ljh* @Description:获取任意天后的时间* @DateTime: 18:52 2022/11/23* @Params: day ...
最新文章
- p3c插件 离线安装_IntelliJ IDEA18个常用插件,动图演示,让你效率翻倍!
- Linux提权CVE-2022-0847分析
- 《Head First设计模式》第四章笔记 工厂模式
- [VBA] 设置行高和列宽,以及全选单元格
- Python基础(三)文件操作和处理json
- 目录、路径、虚拟路径
- 通用时区:你应该知道的数据库时区知识
- 马希荣计算机应用,天津师范大学硕士研究生导师:马希荣
- System.Diagnostics.debug.Assert(条件)的使用
- FCK添加远程图片自动下载
- Atitit 知识聚合的方法大总结 目录 1. 什么是聚合 汇聚	1 2. 聚合化应用场景	2 2.1. 一站式	2 3. 知识聚合的历史与趋势
- C语言(从入门到精通)
- b站视频解析php,B站视频解析套路
- java舆情分析_基于Java实现网络舆情分析系统的研究与实现
- DAHnbsp;CEO:华尔街金融公司比区…
- 高德地图api的自定义地点标注
- Unity模型与动画
- Pod 污点和容忍度
- 【下载Tomcat旧版本】
- pid刘金琨matlab仿真