Go-package1-time-用法

Go package(1) time 用法golang使用的版本: go version go1.10.3 一:功能介绍time的一些功能,比如时区,像linux中的定时器,时间计算等 格式化时间时区(Location)时间计算TickerTimer(定时器)Time一般分为时间Time 和 时段Duration 二:Time 结构体time结构体定义: type Time struct { wall unit64 //表示距离公元1年1月1日00:00:00UTC的秒数 ext int64 //表示纳秒 loc *Location //代表时区,主要处理偏移量。因为不同的时区,对应的时间不一样}上面的loc表示时区, 那什么是时区呢?因为地球是圆的,所以同一个时刻,在地球的一边是白天,一边是黑夜。而因为人类使用一天 24 小时的制度,所以,在地球对角的两边就应该差了 12 的小时才对。由于同一个时间点上面, 整个地球的时间应该都不一样,为了解决这个问题,所以可以想见的,地球就被分成 24 个时区了,因为绕地球一圈是 360 度角,这 360 度角共分为 24 个时区,当然一个时区就是 15 度角啦! 又由于是以格林威治时间为标准时间(Greenwich Mean Time, GMT 时间),加上地球自转的关系,因此,在格林威治以东的区域时间是比较快的(+小时), 而以西的地方当然就是较慢啰!UTC又是什么 ?在计算时间的时候,最准确的计算应该是使用‘原子震荡周期’所计算的物理时钟了 (Atomic Clock, 也被称为原子钟),这也被定义为标准时间 (International Atomic Time)。而我们常常看见的 UTC 也就是 Coordinated Universal Time (协和标准时间)就是利用这种 Atomic Clock 为基准所定义出来的正确时间。例如 1999 年在美国启用的原子钟 NIST F-1, 他所产生的时间误差每两千年才差一秒钟!真的是很准呐!这个 UTC 标准时间是以 GMT 这个时区为主的喔!所以本地时间与 UTC 时间的时差就是本地时间与 GMT 时间的时差就是了!UTC + 时区差 = 本地时间,国内一般使用的是北京时间,与UTC的时间关系如下:UTC + 8个小时 = 北京时间更多关于时间的内容请查看鸟哥的私房菜 ...

June 30, 2019 · 4 min · jiezi

php-学习笔记之日期时间操作一箩筐

格式化日期时间date : 格式化日期时间场景将当前日期时间或者特定日期时间格式化输出为特定格式的字符串,常用于人性化展示信息. 说明返回给定时间戳格式化后所产生的日期时间字符串,如果没有给出时间戳则默认使用本地当前时间. 备注格式说明返回值示例Y4 位数字完整表示的年份2019y2 位数字表示的年份19M三个字母缩写表示的月份Jan 到 Decm数字表示的月份,有前导零01 到 12D星期中的第几天,文本表示,3个字母Mon 到 Sund月份中的第几天,有前导零的 2 位数字01 到 31H小时,24 小时格式,有前导零00 到 23h小时,12 小时格式,有前导零01 到 12I是否为夏令时如果是夏令时为1 ,否则为 0i有前导零的分钟数00 到 59S每月天数后面的英文后缀,2 个字符st,nd,rd 或者 th ,可以和 j 一起用s秒数,有前导零00 到 59常用格式// 形如 2019-05-31 12:00:00echo date("Y-m-d H:i:s");// 形如 2019/05/31 12:00:00echo date("Y/m/d H:i:s");// 形如 2019年05月31日 12时00分00秒echo date("Y年m月d日 H时i分s秒");示例<?php// 设置当前时区为上海时区date_default_timezone_set("Asia/Shanghai");// 获取当前时区 : Asia/Shanghaiecho "当前时区 : ".date_default_timezone_get()."<br/>";// `Y年m月d日 H时i分s秒` 格式化当前时间 : 2019年05月30日 22时32分46秒echo "当前时间 : ".date("Y年m月d日 H时i分s秒")."<br/>";// `Y-m-d H:i:s` 格式化当前时间 : 2019-05-30 22:32:46echo "当前时间 : ".date("Y-m-d H:i:s")."<br/>";// `w` 星期中的第几天,数字表示: 0(表示星期天)到 6(表示星期六)switch (date("w")) { case '0': $dayStr = "日"; break; case '1': $dayStr = "一"; break; case '2': $dayStr = "二"; break; case '3': $dayStr = "三"; break; case '4': $dayStr = "四"; break; case '5': $dayStr = "五"; break; case '6': $dayStr = "六"; break; default: $dayStr = "未知"; break;} // 2019年05月30日 星期四echo "当前时间 : ".date("Y年m月d日")." 星期".$dayStr."<br/>";echo "<hr/>";// `z` 年份中的第几天 : 今天是全年的第149天echo "今天是全年的第".date("z")."天<br/>";// `W` ISO-8601 格式年份中的第几周,每周从星期一开始 : 本周是全年的第22周echo "本周是全年的第".date("W")."周<br/>";// `t` 指定的月份有几天 : 本月共有31天echo "本月共有".date("t")."天<br/>";?>日期转化时间戳time : 返回当前的 Unix 时间戳场景获取当前日期时间或特定日期时间的时间戳,常用于日期时间之间的相互转换. ...

May 31, 2019 · 2 min · jiezi

Go-定时器延时触发器

Go 可以借助 time.After/time.Ticker 来实现延迟/定时触发器,主要原理是借助无缓冲channel无数据时读取操作会阻塞当前协程,Go会在给定的时间后向channel中写入一些数据(当前时间),故阻塞的协程可以恢复运行,达到延迟或定时执行的功能。 延迟执行time.After(d Duration) 好像不如直接用 time.Sleep(d Duration)舒服,但存在即合理,time.After(d Duration)的强大之处在于是基于channel的,可以在不同的协程间同步传递。 package mainimport ( "time" "fmt")func main() { fmt.Println(time.Now().Format("2006-01-02 15:04:05")) // create a nobuf channel and a goroutine `timer` will write it after 2 seconds timeAfterTrigger = time.After(time.Second * 2) // will be suspend but we have `timer` so will be not deadlocked curTime, _ := <-timeAfterTrigger // print current time fmt.Println(curTime.Format("2006-01-02 15:04:05"))}定时执行time.Ticker 的使用分两种场景:执行几次后退出 和 循环执行不退出,执行几次就退出的话我们需要需要回收 time.Ticker。 ...

May 23, 2019 · 1 min · jiezi

MySQL时间类型和模式

当我在MySQL数据库中尝试插入一条带有时间戳的数据时报错: mysql> insert into alarm_service values (6, '1970-01-01 08:00:00'); ERROR 1292 (22007): Incorrect datetime value: '1970-01-01 08:00:00' for column 'time' at row 1# 查看表结构mysql> show create table alarm_service;+---------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+| Table | Create Table |+---------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+| alarm_service | CREATE TABLE `alarm_service` ( `id` int(11) NOT NULL AUTO_INCREMENT, `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 |+---------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+1 row in set (0.00 sec)我们可以发现错误信息提示是时间值错误,但是我们这明显是一个合法的时间点啊。 ...

April 23, 2019 · 2 min · jiezi

go 本周周一的获取

time.Weekday类型可以做运算,强制转int,会得到偏差数。默认是 Sunday 开始到 Saturday 算 0,1,2,3,4,5,6所以只有Monday减去Sunday的时候是正数,特殊处理下就可以了。package dateimport ( “fmt” “time”)func WeekDayTest() { now := time.Now() offset := int(time.Monday - now.Weekday()) if offset > 0 { offset = -6 } weekStart := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, offset) fmt.Println(weekStart)}

March 18, 2019 · 1 min · jiezi

Golang 日期/时间包的使用

golang 的日期时间包:time 的使用方式。time package 包含了 time.Time 时间对象 及 构建此时间对象的一些方法(time.Unix(), time.Parse())golang 可精确到 nanosecond,故相应的函数返回值或参数都已纳秒为单位,我们可以借助time.ParseDuration(durationString string)友好的生成纳秒度量的时间跨度值golang 的时间格式串Layout固定为 2006-01-02 15:04:05golang 默认使用 Local 即本地时区,可以通过 time.LoadLocation(zoneName string) (*Location, error)来设定时区时区构建/格式化模式串// 构建时区var timeLocation *time.LocationtimeLocation, _ = time.LoadLocation("") //UTCtimeLocation, _ = time.LoadLocation(“UTC”) //UTCtimeLocation, _ = time.LoadLocation(“Local”) //LocaltimeLocation, _ = time.LoadLocation(“Asia/Shanghai”) //使用时区码//golang的时间格式化patternvar timeLayout = “2006-01-02 15:04:05"当前时间对象// 获取当前时间对象var timer time.Timetimer = time.Now()// 为时间设定时区 可以通过 timer.Local()/timer.UTC() 快速设定时区timer.In(timeLocation)获取秒级时间戳/纳秒级时间戳// 获取当前秒级时间戳var curTimestamp int64curTimestamp = timer.Unix()println(“current timestamp:” + strconv.FormatInt(curTimestamp, 10))// 获取当前纳秒及时间戳 1秒=1000毫秒=1000,000微妙=1000,000,000纳秒var curNanoTimestamp int64curNanoTimestamp = timer.UnixNano()println(“current nano timestamp:” + strconv.FormatInt(curNanoTimestamp, 10))获取本地时间的时区/CST标准时间/自定义格式// 获取本地时间的时区/快速获取时区时间/自定义格式timeZone, _ := timer.Zone()fmt.Printf(“time zone: %s\n”, timeZone)fmt.Printf(“time location: %s\n”, timer.Location())fmt.Printf(“time in local zone: %s\n”, timer.Local().String())fmt.Printf(“time in utc zone: %s\n”, timer.UTC().String())fmt.Printf(“time: %s\n”, timer.String())fmt.Printf(“time formatted: %s\n”, timer.Format(“2006-01-02 15:04:05”))获取当前的年/月/日 时:分:秒 纳秒// 获取当前的年/月/日 时:分:秒 纳秒fmt.Printf(“current year: %d\n”, timer.Year())fmt.Printf(“current month: %d %s\n”, timer.Month(), timer.Month()) //返回的Month对象fmt.Printf(“current day: %d\n”, timer.Day())fmt.Printf(“current hour: %d\n”, timer.Hour())fmt.Printf(“current minute: %d\n”, timer.Minute())fmt.Printf(“current second: %d\n”, timer.Second())fmt.Printf(“current nanosecond: %d\n”, timer.Nanosecond())获取当前时间/日期// 获取当前时间/日期curHour, curMinute, curSecond := timer.Clock()fmt.Printf(“current clock: %d:%02d:%02d\n”, curHour, curMinute, curSecond)curYear, curMonth, curDay := timer.Date()fmt.Printf(“current date: %d-%02d-%02d\n”, curYear, curMonth, curDay)编辑时间/求两个日期的时间差time.ParseDuration(durationString string)可以方便我们使用语义构建时间跨度值,数值单位为纳秒,比如:timeDuration, _ := time.ParseDuration(“24h”)timeDuration, _ := time.ParseDuration(“12m”)timeDuration, _ := time.ParseDuration(“6s”)timeDuration, _ := time.ParseDuration(“1ms”)timeDuration, _ := time.ParseDuration(“1us”)timeDuration, _ := time.ParseDuration(“1ns”)// 已当前时间为基增长年/月/日后的时间对象timerAdded := timer.AddDate(1, 2, 3)curYear, curMonth, curDay = timerAdded.Date()fmt.Printf(“current date: %d-%02d-%02d\n”, curYear, curMonth, curDay)// 以当前时间为基增长N纳秒后的时间对象 比如增长了一天timeDuration, _ := time.ParseDuration(“24h”)timerAdded = timer.Add(timeDuration)// 计算两个时间的差值 返回的是纳秒 按需求自行计算其他单位// Duration is type of int64 and nanosecondstimeDuration = timerAdded.Sub(timer)fmt.Printf(“days duration between %s~%s: %d\n”, timerAdded.Format(timeLayout), timer.Format(timeLayout), timeDuration/1000/1000/1000/24/60/60)使用 时间字符串 / Unix Timestamp 构建时间对象// 使用时间串获取时间对象timer, _ = time.Parse(timeLayout, “2018-08-08 08:08:08”)// 使用时间串获取时间对象 并设定时区timer, _ = time.ParseInLocation(timeLayout, “2018-08-08 08:08:08”, timeLocation)// 使用Unix时间戳构建时间对象timer = time.Unix(1552368806, 0) //2019-03-12 13:33:26的Unix时间戳fmt.Println(timer.Format(timeLayout))获取当前时间是本年第几天 本周第几天注意周日 的 Weekday编号为 0// 获取当前时间是本年第几天 本周第几天fmt.Printf(“year day: %d, week day: %d\n”, timer.YearDay(), timer.Weekday())使用表征字符串转换时间跨度// 使用表征字符串转换时间跨度timeDuration, _ = time.ParseDuration(“300s”)fmt.Printf(“nanosecond: %d\n”, timeDuration)timeDuration, _ = time.ParseDuration(“300us”)fmt.Printf(“nanosecond: %d\n”, timeDuration) ...

March 12, 2019 · 2 min · jiezi

Lambda表达式与Stream流 (终)

package com.java.design.java8;import org.junit.Before;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringRunner;import java.time.;import java.time.format.DateTimeFormatter;import java.time.temporal.ChronoField;import java.util.;import java.util.concurrent.CompletableFuture;import java.util.stream.Collectors;import java.util.stream.IntStream;/** * @author 陈杨 * / @SpringBootTest@RunWith(SpringRunner.class)public class LambdaInfo {一、Lambda表达式与Stream流/ A lambda expression can be understood as a concise representation of an anonymous function that can be passed around: it doesn’t have a name, but it has a list of parameters, a body, a return type, and also possibly a list of exceptions that can be thrown. That’s one big definition; let’s break it down: Anonymous: We say anonymous because it doesn’t have an explicit name like a method would normally have: less to write and think about! Function: We say function because a lambda isn’t associated with a particular class like a method is. But like a method, a lambda has a list of parameters, a body, a return type, and a possible list of exceptions that can be thrown. Passed around: A lambda expression can be passed as argument to a method or stored in a variable. Concise: You don’t need to write a lot of boilerplate like you do for anonymous classes.// Stream : A sequence of elements from a source that supports data processing operations. Sequence of elements Source Pipelining Internal iteration Traversable only once Collections: external interation using an interator behind the scenes*/二、初始化测试数据private List<Integer> list;@Beforepublic void init() { list = IntStream.rangeClosed(1, 100).boxed().collect(Collectors.toList()); list.sort(Collections.reverseOrder());}三、各种API1.allMatch@Testpublic void testLambdaInfo() { System.out.println(">———————Match方法———————-<"); // 一、Match方法 // Returns whether all elements of this stream match the provided predicate. Optional.of(list.stream().mapToInt(Integer::intValue).allMatch(i -> i > 0)) .ifPresent(System.out::println); // Returns whether any elements of this stream match the provided predicate. Optional.of(list.stream().mapToInt(Integer::intValue).anyMatch(i -> i > 0)) .ifPresent(System.out::println); // Returns whether no elements of this stream match the provided predicate.. Optional.of(list.stream().mapToInt(Integer::intValue).noneMatch(i -> i > 0)) .ifPresent(System.out::println);2、findSystem.out.println(">——————–Find方法———————–<");// 二、Find方法// Returns an Optional describing the first element of this stream,// or an empty Optional if the stream is empty.// If the stream has no encounter order, then any element may be returned.list.stream().mapToInt(Integer::intValue).filter(i -> i > 10).findFirst() .ifPresent(System.out::println);// Returns an Optional describing some element of the stream, or an empty Optional if the stream is empty.list.stream().mapToInt(Integer::intValue).filter(i -> i > 10).findAny() .ifPresent(System.out::println);3、reduceSystem.out.println(">———————Reduce方法———————-<");// 三、Reduce方法// Performs a reduction on the elements of this stream, using the provided identity value// and an associative accumulation function, and returns the reduced value.// 求和System.out.println(list.stream().reduce(0, Integer::sum));list.stream().mapToInt(Integer::intValue).reduce(Integer::sum) .ifPresent(System.out::println);// 求最大值System.out.println(list.stream().reduce(0, Integer::max));list.stream().mapToInt(Integer::intValue).reduce(Integer::max) .ifPresent(System.out::println);// 求最小值System.out.println(list.stream().reduce(0, Integer::min));list.stream().mapToInt(Integer::intValue).reduce(Integer::min) .ifPresent(System.out::println); System.out.println(">——————————————-<"); }4、CompletableFuture API@Testpublic void testCompletableFuture() { // 四、CompletableFuture API /* * Returns a new CompletableFuture that is asynchronously completed by a task * running in the given executor with the value obtained by calling the given Supplier. */ CompletableFuture.supplyAsync(list.stream().mapToInt(Integer::intValue)::sum, System.out::println); Optional.of(CompletableFuture.supplyAsync(list.stream().mapToInt(Integer::intValue)::sum) .complete(55)).ifPresent(System.out::println); // thenAccept 无返回值 Consumer<? super T> action CompletableFuture.supplyAsync(list.stream().mapToInt(Integer::intValue)::sum) .thenAccept(System.out::println); // thenApply 有返回值 Function<? super T,? extends U> fn CompletableFuture.supplyAsync(() -> list.stream().mapToInt(Integer::intValue)) .thenApply(IntStream::sum).thenAccept(System.out::println); // 对元素及异常进行处理 BiFunction<? super T, Throwable, ? extends U> fn CompletableFuture.supplyAsync(() -> list.stream().mapToInt(Integer::intValue)) .handle((i, throwable) -> “handle:\t” + i.sum()).thenAccept(System.out::println); // whenCompleteAsync 完成时执行 BiConsumer<? super T, ? super Throwable> action CompletableFuture.supplyAsync(list.stream().mapToInt(Integer::intValue)::sum) .whenCompleteAsync((value, throwable) -> System.out.println(“whenCompleteAsync:\t” + value)); // 组合CompletableFuture 将前一个结果作为后一个输入参数 (参照 组合设计模式) CompletableFuture.supplyAsync(() -> list.stream().mapToInt(Integer::intValue)) .thenCompose(i -> CompletableFuture.supplyAsync(i::sum)).thenAccept(System.out::println); // 合并CompletableFuture CompletableFuture.supplyAsync(list.stream().mapToInt(Integer::intValue)::sum) .thenCombine(CompletableFuture.supplyAsync(() -> list.stream() .mapToDouble(Double::valueOf).sum()), Double::sum).thenAccept(System.out::println); // 合并CompletableFuture CompletableFuture.supplyAsync(list.stream().mapToInt(Integer::intValue)::sum) .thenAcceptBoth(CompletableFuture.supplyAsync(list.stream() .mapToDouble(Double::valueOf)::sum), (r1, r2) -> System.out.println(“thenAcceptBoth:\t” + r1 + “\t” + r2)); // 2个CompletableFuture运行完毕后运行Runnable CompletableFuture.supplyAsync(() -> { System.out.println(Thread.currentThread().getName() + “\tis running”); return list.stream().mapToInt(Integer::intValue).sum(); }) .runAfterBoth( CompletableFuture.supplyAsync(() -> { System.out.println(Thread.currentThread().getName() + “\tis running”); return list.stream().mapToDouble(Double::valueOf).sum(); }), () -> System.out.println(“The 2 method have done”)); // 2个CompletableFuture 有一个运行完就执行Runnable CompletableFuture.supplyAsync(() -> { System.out.println(Thread.currentThread().getName() + “\tis running”); return list.stream().mapToInt(Integer::intValue).sum(); }) .runAfterEither( CompletableFuture.supplyAsync(() -> { System.out.println(Thread.currentThread().getName() + “\tis running”); return list.stream().mapToDouble(Double::valueOf).sum(); }), () -> System.out.println(“The 2 method have done”)); // 2个CompletableFuture 有一个运行完就执行Function<? super T, U> fn CompletableFuture.supplyAsync( list.stream().mapToInt(Integer::intValue).max()::getAsInt) .applyToEither( CompletableFuture.supplyAsync(list.stream().mapToInt(Integer::intValue).min()::getAsInt) , v -> v * 10) .thenAccept(System.out::println); // 2个CompletableFuture 有一个运行完就执行Consumer<? super T> action CompletableFuture.supplyAsync( list.stream().mapToInt(Integer::intValue).max()::getAsInt) .acceptEither( CompletableFuture.supplyAsync(list.stream().mapToInt(Integer::intValue).min()::getAsInt) , System.out::println); // 将集合中每一个元素都映射成为CompletableFuture<Integer>对象 List<CompletableFuture<Integer>> collect = list.stream().map(i -> CompletableFuture.supplyAsync(i::intValue)) .collect(ArrayList::new, ArrayList::add, ArrayList::addAll); // 集合转数组 CompletableFuture[] completableFutures = collect.toArray(CompletableFuture[]::new); // 有一个task执行完毕 CompletableFuture.anyOf(completableFutures) .thenRun(() -> System.out.println(“有一个task执行完毕—>first done”)); // 有且仅有所有task执行完毕 CompletableFuture.allOf(completableFutures) .thenRun(() -> System.out.println(“有且仅有所有task执行完毕—>done”));}5、Java.time API @Test public void testLocalDateTime() { // 五、Java.time API LocalDate localDate = LocalDate.of(2019, 12, 1); // 当前时间 Optional.of(LocalDate.now()).ifPresent(System.out::println); // 年份 Optional.of(localDate.getYear()).ifPresent(System.out::println); OptionalInt.of(localDate.get(ChronoField.YEAR)).ifPresent(System.out::println); // 月份 (Jan–>Dec) Optional.of(localDate.getMonth()).ifPresent(System.out::println); // 月份(1–>12) Optional.of(localDate.getMonthValue()).ifPresent(System.out::println); OptionalInt.of(localDate.get(ChronoField.MONTH_OF_YEAR)).ifPresent(System.out::println); // 年中的第几天 Optional.of(localDate.getDayOfYear()).ifPresent(System.out::println); OptionalInt.of(localDate.get(ChronoField.DAY_OF_YEAR)).ifPresent(System.out::println); // 月中的第几天 Optional.of(localDate.getDayOfMonth()).ifPresent(System.out::println); OptionalInt.of(localDate.get(ChronoField.DAY_OF_MONTH)).ifPresent(System.out::println); // 星期几(Mon–>Sun) Optional.of(localDate.getDayOfWeek()).ifPresent(System.out::println); // 星期几(1–>7) OptionalInt.of(localDate.get(ChronoField.DAY_OF_WEEK)).ifPresent(System.out::println); // 时代(公元前、后) CE BCE Optional.of(localDate.getEra()).ifPresent(System.out::println); // 时代(公元前、后) 1—>CE 0—>BCE Optional.of(localDate.getEra().getValue()).ifPresent(System.out::println); OptionalInt.of(localDate.get(ChronoField.ERA)).ifPresent(System.out::println); // ISO年表 Optional.of(localDate.getChronology().getId()).ifPresent(System.out::println); // 当前时间 LocalTime time = LocalTime.now(); // 时 OptionalInt.of(time.getHour()).ifPresent(System.out::println); OptionalInt.of(time.get(ChronoField.HOUR_OF_DAY)).ifPresent(System.out::println); // 分 OptionalInt.of(time.getMinute()).ifPresent(System.out::println); OptionalInt.of(time.get(ChronoField.MINUTE_OF_DAY)).ifPresent(System.out::println); // 秒 OptionalInt.of(time.getSecond()).ifPresent(System.out::println); OptionalInt.of(time.get(ChronoField.SECOND_OF_DAY)).ifPresent(System.out::println); // 纳秒 OptionalInt.of(time.getNano()).ifPresent(System.out::println); OptionalLong.of(time.getLong(ChronoField.NANO_OF_SECOND)).ifPresent(System.out::println); // 中午时间 Optional.of(LocalTime.NOON).ifPresent(System.out::println); // 午夜时间 Optional.of(LocalTime.MIDNIGHT).ifPresent(System.out::println); // 自定义格式化时间 DateTimeFormatter customDateTimeFormatter = DateTimeFormatter.ofPattern(“yyyy-MM-dd HH:mm:ss E”); LocalDateTime localDateTime = LocalDateTime.of(localDate, time); Optional.of(localDateTime.format(customDateTimeFormatter)).ifPresent(System.out::println); // 根据传入的文本匹配自定义指定格式进行解析 Optional.of(LocalDateTime.parse(“2019-12-25 12:30:00 周三”, customDateTimeFormatter)) .ifPresent(System.out::println); // 时间点 Instant Instant start = Instant.now(); try { Thread.sleep(10_000); } catch (InterruptedException e) { e.printStackTrace(); } Instant end = Instant.now(); // Duration 时间段 Duration duration = Duration.between(start, end); OptionalLong.of(duration.toNanos()).ifPresent(System.out::println); // Period 时间段 Period period = Period.between(LocalDate.now(), localDate); OptionalInt.of(period.getYears()).ifPresent(System.out::println); OptionalInt.of(period.getMonths()).ifPresent(System.out::println); OptionalInt.of(period.getDays()).ifPresent(System.out::println); // The Difference Between Duration And Period // Durations and periods differ in their treatment of daylight savings time when added to ZonedDateTime. // A Duration will add an exact number of seconds, thus a duration of one day is always exactly 24 hours. // By contrast, a Period will add a conceptual day, trying to maintain the local time. }} ...

March 11, 2019 · 4 min · jiezi

javascript的date操作使用

DateDate 对象用于处理日期与时间。构造方法new Date();new Date(value);new Date(dateString);new Date(year, month[, day[, hour[, minutes[, seconds[, milliseconds]]]]]);参数:value代表自1970年1月1日00:00:00 (世界标准时间) 起经过的毫秒数。dateString表示日期的字符串值。该字符串应该能被 Date.parse() 方法识别(符合 IETF-compliant RFC 2822 timestamps 或 version of ISO8601)。year代表年份的整数值。为了避免2000年问题最好指定4位数的年份; 使用 1998, 而不要用 98.month代表月份的整数值从0(1月)到11(12月)。day代表一个月中的第几天的整数值,从1开始。hour代表一天中的小时数的整数值 (24小时制)。minute分钟数。second秒数。millisecond表示时间的毫秒部分的整数值。需要注意的是只能通过调用 Date 构造函数来实例化日期对象:以常规函数调用它(即不加 new 操作符)将会返回一个字符串,而不是一个日期对象。另外,不像其他JavaScript 类型,Date 对象没有字面量格式。当Date作为构造函数调用并传入多个参数时,如果数值大于合理范围时(如月份为13或者分钟数为70),相邻的数值会被调整。比如 new Date(2013, 13, 1)等于new Date(2014, 1, 1),它们都表示日期2014-02-01(注意月份是从0开始的)。其他数值也是类似,new Date(2013, 2, 1, 0, 70)等于new Date(2013, 2, 1, 1, 10),都表示时间2013-03-01T01:10:00。如果没有输入任何参数,则Date的构造器会依据系统设置的当前时间来创建一个Date对象。如果提供了至少两个参数,其余的参数均会默认设置为1(如果没有提供day参数)或者0。JavaScript的时间是由世界标准时间(UTC)1970年1月1日开始,用毫秒计时,一天由86,400,000毫秒组成。Date对象的范围是-100,000,000天至100,000,000天(等效的毫秒值)。JavaScript的Date对象为跨平台提供了统一的行为。时间属性可以在不同的系统中表示相同的时刻,而如果使用了本地时间对象,则反映当地的时间。JavaScript 的Date对象提供了数个UTC时间的方法,也相应提供了当地时间的方法。UTC,也就是我们所说的格林威治时间,指的是time中的世界时间标准。而当地时间则是指执行JavaScript的客户端电脑所设置的时间。以一个函数的形式来调用JavaScript的Date对象(i.e., 不使用 new 操作符)会返回一个代表当前日期和时间的字符串。dateString表示日期的字符串值。该字符串应该能被 Date.parse() 方法识别(符合 IETF-compliant RFC 2822 timestamps 或 version of ISO8601)。所以需要确认datestring的类型。IETF-compliant RFC 2822 timestamps最初的datestring的只支持:时间字符串Date and Time Specification Date and time occur in several header fields. This section specifies the syntax for a full date and time specification. Though folding white space is permitted throughout the date-time specification, it is RECOMMENDED that a single space be used in each place that FWS appears (whether it is required or optional); some older implementations may not interpret other occurrences of folding white space correctly.date-time = [ day-of-week “,” ] date FWS time [CFWS]day-of-week = ([FWS] day-name) / obs-day-of-weekday-name = “Mon” / “Tue” / “Wed” / “Thu” / “Fri” / “Sat” / “Sun"date = day month yearyear = 4DIGIT / obs-yearmonth = (FWS month-name FWS) / obs-monthmonth-name = “Jan” / “Feb” / “Mar” / “Apr” / “May” / “Jun” / “Jul” / “Aug” / “Sep” / “Oct” / “Nov” / “Dec"day = ([FWS] 12DIGIT) / obs-daytime = time-of-day FWS zonetime-of-day = hour “:” minute [ “:” second ]hour = 2DIGIT / obs-hourminute = 2DIGIT / obs-minutesecond = 2DIGIT / obs-secondzone = (( “+” / “-” ) 4DIGIT) / obs-zoneThe day is the numeric day of the month. The year is any numeric year 1900 or later. The time-of-day specifies the number of hours, minutes, and optionally seconds since midnight of the date indicated. The date and time-of-day SHOULD express local time. The zone specifies the offset from Coordinated Universal Time (UTC, formerly referred to as “Greenwich Mean Time”) that the date and time-of-day represent. The “+” or “-” indicates whether the time-of-day is ahead of (i.e., east of) or behind (i.e., west of) Universal Time. The first two digits indicate the number of hours difference from Universal Time, and the last two digits indicate the number of minutes difference from Universal Time. (Hence, +hhmm means +(hh * 60 + mm) minutes, and -hhmm means -(hh * 60 + mm) minutes). The form “+0000” SHOULD be used to indicate a time zone at Universal Time. Though “-0000” also indicates Universal Time, it is used to indicate that the time was generated on a system that may be in a local time zone other than Universal Time and therefore indicates that the date-time contains no information about the local time zone. A date-time specification MUST be semantically valid. That is, the day-of-the-week (if included) MUST be the day implied by the date, the numeric day-of-month MUST be between 1 and the number of days allowed for the specified month (in the specified year), the time-of-day MUST be in the range 00:00:00 through 23:59:60 (the number of seconds allowing for a leap second; see [STD12]), and the zone MUST be within the range -9959 through +9959.所以可以得出结论:最开始的js仅支持以下格式的datestring【需要注意的是各个浏览器实现不一致,所以可能会支持其他的格式的datestring】Sun 30 Dec 2018 19:42:44 +0800看起来和console.log里面的输出有一点不一致;Sun Dec 30 2018 19:42:44 GMT+0800 (中国标准时间)version of ISO8601在es5开始,添加了ISO8601格式的支持;Date Time String FormatECMAScript defines a string interchange format for date-times based upon a simplification of the ISO 8601 Extended Format. The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZWhere the fields are as follows:YYYY is the decimal digits of the year 0000 to 9999 in the Gregorian calendar.- “-” (hyphen) appears literally twice in the string.MM is the month of the year from 01 (January) to 12 (December).DD is the day of the month from 01 to 31.T “T” appears literally in the string, to indicate the beginning of the time element.HH is the number of complete hours that have passed since midnight as two decimal digits from 00 to 24.: “:” (colon) appears literally twice in the string.mm is the number of complete minutes since the start of the hour as two decimal digits from 00 to 59.ss is the number of complete seconds since the start of the minute as two decimal digits from 00 to 59.. “.” (dot) appears literally in the string.sss is the number of complete milliseconds since the start of the second as three decimal digits.Z is the time zone offset specified as “Z” (for UTC) or either “+” or “-” followed by a time expression HH:mmThis format includes date-only forms:YYYYYYYY-MMYYYY-MM-DDIt also includes “date-time” forms that consist of one of the above date-only forms immediately followed by one of the following time forms with an optional time zone offset appended:THH:mmTHH:mm:ssTHH:mm:ss.sssAll numbers must be base 10. If the MM or DD fields are absent “01” is used as the value. If the HH, mm, or ss fields are absent “00” is used as the value and the value of an absent sss field is “000”. The value of an absent time zone offset is “Z”.Illegal values (out-of-bounds as well as syntax errors) in a format string means that the format string is not a valid instance of this format.NOTE 1 As every day both starts and ends with midnight, the two notations 00:00 and 24:00 are available to distinguish the two midnights that can be associated with one date. This means that the following two notations refer to exactly the same point in time: 1995-02-04T24:00 and 1995-02-05T00:00NOTE 2 There exists no international standard that specifies abbreviations for civil time zones like CET, EST, etc. and sometimes the same abbreviation is even used for two very different time zones. For this reason, ISO 8601 and this format specifies numeric representations of date and time.datestring的格式可以是如下:[date][date]T[time][date]T[time]Z[date]Ttime[0800]其中[date]可以是:YYYYYYYY-MMYYYY-MM-DD而[time]可以是一下:THH:mmTHH:mm:ssTHH:mm:ss.sss可以说[date]是必须有的,其他的都是可以没有,会取默认值,当然各个浏览器内部实现的不一致,所以可能还会出现不一致的问题;API列表Date.UTC()Date.now()Date.parse()Date.prototype.getDate()Date.prototype.getDay()Date.prototype.getFullYear()Date.prototype.getHours()Date.prototype.getMilliseconds()Date.prototype.getMinutes()Date.prototype.getMonth()Date.prototype.getSeconds()Date.prototype.getTime()Date.prototype.getTimezoneOffset()Date.prototype.getUTCDate()Date.prototype.getUTCDay()Date.prototype.getUTCFullYear()Date.prototype.getUTCHours()Date.prototype.getUTCMilliseconds()Date.prototype.getUTCMinutes()Date.prototype.getUTCMonth()Date.prototype.getUTCSeconds()Date.prototype.getYear()Date.prototype.setDate()Date.prototype.setFullYear()Date.prototype.setHours()Date.prototype.setMilliseconds()Date.prototype.setMinutes()Date.prototype.setMonth()Date.prototype.setSeconds()Date.prototype.setTime()Date.prototype.setUTCDate()Date.prototype.setUTCFullYear()Date.prototype.setUTCHours()Date.prototype.setUTCMilliseconds()Date.prototype.setUTCMinutes()Date.prototype.setUTCMonth()Date.prototype.setUTCSeconds()Date.prototype.setYear()Date.prototype.toDateString()Date.prototype.toGMTString()Date.prototype.toISOString()Date.prototype.toJSON()Date.prototype.toLocaleDateString()Date.prototype.toLocaleFormat()Date.prototype.toLocaleString()Date.prototype.toLocaleTimeString()Date.prototype.toSource()Date.prototype.toString()Date.prototype.toTimeString()Date.prototype.toUTCString()Date.prototype.valueOf()Date.prototype[@@toPrimitive]一元加法|加法+new Date()// 15463354481250+new Date()// “0Tue Jan 01 2019 17:53:17 GMT+0800 (中国标准时间)“二元加法获取date的值;加法运算上图中的NOTE 1说,在步骤5和6中的ToPrimitive调用没有提供hint,除了Date对象之外所有ECMAScript对象将缺少hint的情况当做Number处理;js各个类型的toPrimitive而本文需要看的是date@@toPrimitive 方法可以转换一个 Date 对象到一个原始值。Date()Symbol.toPrimitive==>date.toPrimitive;给出的 Date 的原始值。根据传入参数的不同,可以返回 string 或 number 类型。Date 对象的 @@toPrimitive 方法可以返回一个原始值,或是 string,或是number。如果 hint 是 “string” 或 “default”,@@toPrimitive 将会调用 toString。如果 toString 属性不存在,则调用 valueOf。如果 valueOf 也不存在,则抛出一个TypeError。如果 hint 是 “number”,@@toPrimitive 会首先尝试 valueOf,若失败再尝试 toString。当期望一个原始值却收到一个对象时,JavaScript 可以自动的调用 @@toPrimitive 方法来将一个对象转化成原始值,所以你很少会需要自己调用这个方法。date的toPrimitive调用,不传递hint的时候,默认是string;所以:0+new Date()// “0Tue Jan 01 2019 17:53:17 GMT+0800 (中国标准时间)“一元加法获取date的值’+‘号运算符作为一元运算符时,Expression将进行ToNumber操作。可以看到,此时date的toPrimitive调用,传递hint是number,返回毫秒数;参考: JavaScript 加号运算符详解 ...

January 1, 2019 · 5 min · jiezi