Source file
src/time/example_test.go
1
2
3
4
5 package time_test
6
7 import (
8 "fmt"
9 "math"
10 "time"
11 )
12
13 func expensiveCall() {}
14
15 func ExampleDuration() {
16 t0 := time.Now()
17 expensiveCall()
18 t1 := time.Now()
19 fmt.Printf("The call took %v to run.\n", t1.Sub(t0))
20 }
21
22 func ExampleDuration_Round() {
23 d, err := time.ParseDuration("1h15m30.918273645s")
24 if err != nil {
25 panic(err)
26 }
27
28 round := []time.Duration{
29 time.Nanosecond,
30 time.Microsecond,
31 time.Millisecond,
32 time.Second,
33 2 * time.Second,
34 time.Minute,
35 10 * time.Minute,
36 time.Hour,
37 }
38
39 for _, r := range round {
40 fmt.Printf("d.Round(%6s) = %s\n", r, d.Round(r).String())
41 }
42
43
44
45
46
47
48
49
50
51 }
52
53 func ExampleDuration_String() {
54 fmt.Println(1*time.Hour + 2*time.Minute + 300*time.Millisecond)
55 fmt.Println(300 * time.Millisecond)
56
57
58
59 }
60
61 func ExampleDuration_Truncate() {
62 d, err := time.ParseDuration("1h15m30.918273645s")
63 if err != nil {
64 panic(err)
65 }
66
67 trunc := []time.Duration{
68 time.Nanosecond,
69 time.Microsecond,
70 time.Millisecond,
71 time.Second,
72 2 * time.Second,
73 time.Minute,
74 10 * time.Minute,
75 time.Hour,
76 }
77
78 for _, t := range trunc {
79 fmt.Printf("d.Truncate(%6s) = %s\n", t, d.Truncate(t).String())
80 }
81
82
83
84
85
86
87
88
89
90 }
91
92 func ExampleParseDuration() {
93 hours, _ := time.ParseDuration("10h")
94 complex, _ := time.ParseDuration("1h10m10s")
95 micro, _ := time.ParseDuration("1µs")
96
97 micro2, _ := time.ParseDuration("1us")
98
99 fmt.Println(hours)
100 fmt.Println(complex)
101 fmt.Printf("There are %.0f seconds in %v.\n", complex.Seconds(), complex)
102 fmt.Printf("There are %d nanoseconds in %v.\n", micro.Nanoseconds(), micro)
103 fmt.Printf("There are %6.2e seconds in %v.\n", micro2.Seconds(), micro2)
104
105
106
107
108
109
110 }
111
112 func ExampleSince() {
113 start := time.Now()
114 expensiveCall()
115 elapsed := time.Since(start)
116 fmt.Printf("The call took %v to run.\n", elapsed)
117 }
118
119 func ExampleUntil() {
120 futureTime := time.Now().Add(5 * time.Second)
121 durationUntil := time.Until(futureTime)
122 fmt.Printf("Duration until future time: %.0f seconds", math.Ceil(durationUntil.Seconds()))
123
124 }
125
126 func ExampleDuration_Abs() {
127 positiveDuration := 5 * time.Second
128 negativeDuration := -3 * time.Second
129 minInt64CaseDuration := time.Duration(math.MinInt64)
130
131 absPositive := positiveDuration.Abs()
132 absNegative := negativeDuration.Abs()
133 absSpecial := minInt64CaseDuration.Abs() == time.Duration(math.MaxInt64)
134
135 fmt.Printf("Absolute value of positive duration: %v\n", absPositive)
136 fmt.Printf("Absolute value of negative duration: %v\n", absNegative)
137 fmt.Printf("Absolute value of MinInt64 equal to MaxInt64: %t\n", absSpecial)
138
139
140
141
142
143 }
144
145 func ExampleDuration_Hours() {
146 h, _ := time.ParseDuration("4h30m")
147 fmt.Printf("I've got %.1f hours of work left.", h.Hours())
148
149 }
150
151 func ExampleDuration_Microseconds() {
152 u, _ := time.ParseDuration("1s")
153 fmt.Printf("One second is %d microseconds.\n", u.Microseconds())
154
155
156 }
157
158 func ExampleDuration_Milliseconds() {
159 u, _ := time.ParseDuration("1s")
160 fmt.Printf("One second is %d milliseconds.\n", u.Milliseconds())
161
162
163 }
164
165 func ExampleDuration_Minutes() {
166 m, _ := time.ParseDuration("1h30m")
167 fmt.Printf("The movie is %.0f minutes long.", m.Minutes())
168
169 }
170
171 func ExampleDuration_Nanoseconds() {
172 u, _ := time.ParseDuration("1µs")
173 fmt.Printf("One microsecond is %d nanoseconds.\n", u.Nanoseconds())
174
175
176 }
177
178 func ExampleDuration_Seconds() {
179 m, _ := time.ParseDuration("1m30s")
180 fmt.Printf("Take off in t-%.0f seconds.", m.Seconds())
181
182 }
183
184 var c chan int
185
186 func handle(int) {}
187
188 func ExampleAfter() {
189 select {
190 case m := <-c:
191 handle(m)
192 case <-time.After(10 * time.Second):
193 fmt.Println("timed out")
194 }
195 }
196
197 func ExampleSleep() {
198 time.Sleep(100 * time.Millisecond)
199 }
200
201 func statusUpdate() string { return "" }
202
203 func ExampleTick() {
204 c := time.Tick(5 * time.Second)
205 for next := range c {
206 fmt.Printf("%v %s\n", next, statusUpdate())
207 }
208 }
209
210 func ExampleMonth() {
211 _, month, day := time.Now().Date()
212 if month == time.November && day == 10 {
213 fmt.Println("Happy Go day!")
214 }
215 }
216
217 func ExampleDate() {
218 t := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
219 fmt.Printf("Go launched at %s\n", t.Local())
220
221 }
222
223 func ExampleNewTicker() {
224 ticker := time.NewTicker(time.Second)
225 defer ticker.Stop()
226 done := make(chan bool)
227 go func() {
228 time.Sleep(10 * time.Second)
229 done <- true
230 }()
231 for {
232 select {
233 case <-done:
234 fmt.Println("Done!")
235 return
236 case t := <-ticker.C:
237 fmt.Println("Current time: ", t)
238 }
239 }
240 }
241
242 func ExampleTime_Format() {
243
244 t, err := time.Parse(time.UnixDate, "Wed Feb 25 11:06:39 PST 2015")
245 if err != nil {
246 panic(err)
247 }
248
249 tz, err := time.LoadLocation("Asia/Shanghai")
250 if err != nil {
251 panic(err)
252 }
253
254
255 fmt.Println("default format:", t)
256
257
258 fmt.Println("Unix format:", t.Format(time.UnixDate))
259
260
261 fmt.Println("Same, in UTC:", t.UTC().Format(time.UnixDate))
262
263 fmt.Println("in Shanghai with seconds:", t.In(tz).Format("2006-01-02T15:04:05 -070000"))
264
265 fmt.Println("in Shanghai with colon seconds:", t.In(tz).Format("2006-01-02T15:04:05 -07:00:00"))
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286 do := func(name, layout, want string) {
287 got := t.Format(layout)
288 if want != got {
289 fmt.Printf("error: for %q got %q; expected %q\n", layout, got, want)
290 return
291 }
292 fmt.Printf("%-16s %q gives %q\n", name, layout, got)
293 }
294
295
296 fmt.Printf("\nFormats:\n\n")
297
298
299 do("Basic full date", "Mon Jan 2 15:04:05 MST 2006", "Wed Feb 25 11:06:39 PST 2015")
300 do("Basic short date", "2006/01/02", "2015/02/25")
301
302
303
304
305 do("AM/PM", "3PM==3pm==15h", "11AM==11am==11h")
306
307
308
309
310
311 t, err = time.Parse(time.UnixDate, "Wed Feb 25 11:06:39.1234 PST 2015")
312 if err != nil {
313 panic(err)
314 }
315
316
317 do("No fraction", time.UnixDate, "Wed Feb 25 11:06:39 PST 2015")
318
319
320
321
322
323 do("0s for fraction", "15:04:05.00000", "11:06:39.12340")
324
325
326 do("9s for fraction", "15:04:05.99999999", "11:06:39.1234")
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344 }
345
346 func ExampleTime_Format_pad() {
347
348 t, err := time.Parse(time.UnixDate, "Sat Mar 7 11:06:39 PST 2015")
349 if err != nil {
350 panic(err)
351 }
352
353
354 do := func(name, layout, want string) {
355 got := t.Format(layout)
356 if want != got {
357 fmt.Printf("error: for %q got %q; expected %q\n", layout, got, want)
358 return
359 }
360 fmt.Printf("%-16s %q gives %q\n", name, layout, got)
361 }
362
363
364 do("Unix", time.UnixDate, "Sat Mar 7 11:06:39 PST 2015")
365
366
367
368
369
370 do("No pad", "<2>", "<7>")
371
372
373 do("Spaces", "<_2>", "< 7>")
374
375
376 do("Zeros", "<02>", "<07>")
377
378
379
380
381 do("Suppressed pad", "04:05", "06:39")
382
383
384
385
386
387
388
389
390 }
391
392 func ExampleTime_GoString() {
393 t := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
394 fmt.Println(t.GoString())
395 t = t.Add(1 * time.Minute)
396 fmt.Println(t.GoString())
397 t = t.AddDate(0, 1, 0)
398 fmt.Println(t.GoString())
399 t, _ = time.Parse("Jan 2, 2006 at 3:04pm (MST)", "Feb 3, 2013 at 7:54pm (UTC)")
400 fmt.Println(t.GoString())
401
402
403
404
405
406
407 }
408
409 func ExampleParse() {
410
411
412
413
414
415
416 const longForm = "Jan 2, 2006 at 3:04pm (MST)"
417 t, _ := time.Parse(longForm, "Feb 3, 2013 at 7:54pm (PST)")
418 fmt.Println(t)
419
420
421
422
423 const shortForm = "2006-Jan-02"
424 t, _ = time.Parse(shortForm, "2013-Feb-03")
425 fmt.Println(t)
426
427
428
429
430
431
432
433 t, _ = time.Parse(time.RFC3339, "2006-01-02T15:04:05Z")
434 fmt.Println(t)
435 t, _ = time.Parse(time.RFC3339, "2006-01-02T15:04:05+07:00")
436 fmt.Println(t)
437 _, err := time.Parse(time.RFC3339, time.RFC3339)
438 fmt.Println("error", err)
439
440
441
442
443
444
445
446 }
447
448 func ExampleParseInLocation() {
449 loc, _ := time.LoadLocation("Europe/Berlin")
450
451
452 const longForm = "Jan 2, 2006 at 3:04pm (MST)"
453 t, _ := time.ParseInLocation(longForm, "Jul 9, 2012 at 5:02am (CEST)", loc)
454 fmt.Println(t)
455
456
457 const shortForm = "2006-Jan-02"
458 t, _ = time.ParseInLocation(shortForm, "2012-Jul-09", loc)
459 fmt.Println(t)
460
461
462
463
464 }
465
466 func ExampleUnix() {
467 unixTime := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
468 fmt.Println(unixTime.Unix())
469 t := time.Unix(unixTime.Unix(), 0).UTC()
470 fmt.Println(t)
471
472
473
474
475 }
476
477 func ExampleUnixMicro() {
478 umt := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
479 fmt.Println(umt.UnixMicro())
480 t := time.UnixMicro(umt.UnixMicro()).UTC()
481 fmt.Println(t)
482
483
484
485
486 }
487
488 func ExampleUnixMilli() {
489 umt := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
490 fmt.Println(umt.UnixMilli())
491 t := time.UnixMilli(umt.UnixMilli()).UTC()
492 fmt.Println(t)
493
494
495
496
497 }
498
499 func ExampleTime_Unix() {
500
501 fmt.Println(time.Unix(1e9, 0).UTC())
502 fmt.Println(time.Unix(0, 1e18).UTC())
503 fmt.Println(time.Unix(2e9, -1e18).UTC())
504
505 t := time.Date(2001, time.September, 9, 1, 46, 40, 0, time.UTC)
506 fmt.Println(t.Unix())
507 fmt.Println(t.UnixNano())
508
509
510
511
512
513
514
515 }
516
517 func ExampleTime_Round() {
518 t := time.Date(0, 0, 0, 12, 15, 30, 918273645, time.UTC)
519 round := []time.Duration{
520 time.Nanosecond,
521 time.Microsecond,
522 time.Millisecond,
523 time.Second,
524 2 * time.Second,
525 time.Minute,
526 10 * time.Minute,
527 time.Hour,
528 }
529
530 for _, d := range round {
531 fmt.Printf("t.Round(%6s) = %s\n", d, t.Round(d).Format("15:04:05.999999999"))
532 }
533
534
535
536
537
538
539
540
541
542 }
543
544 func ExampleTime_Truncate() {
545 t, _ := time.Parse("2006 Jan 02 15:04:05", "2012 Dec 07 12:15:30.918273645")
546 trunc := []time.Duration{
547 time.Nanosecond,
548 time.Microsecond,
549 time.Millisecond,
550 time.Second,
551 2 * time.Second,
552 time.Minute,
553 10 * time.Minute,
554 }
555
556 for _, d := range trunc {
557 fmt.Printf("t.Truncate(%5s) = %s\n", d, t.Truncate(d).Format("15:04:05.999999999"))
558 }
559
560 midnight := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.Local)
561 _ = midnight
562
563
564
565
566
567
568
569
570
571 }
572
573 func ExampleLoadLocation() {
574 location, err := time.LoadLocation("America/Los_Angeles")
575 if err != nil {
576 panic(err)
577 }
578
579 timeInUTC := time.Date(2018, 8, 30, 12, 0, 0, 0, time.UTC)
580 fmt.Println(timeInUTC.In(location))
581
582 }
583
584 func ExampleLocation() {
585
586 secondsEastOfUTC := int((8 * time.Hour).Seconds())
587 beijing := time.FixedZone("Beijing Time", secondsEastOfUTC)
588
589
590
591
592
593
594 timeInUTC := time.Date(2009, 1, 1, 12, 0, 0, 0, time.UTC)
595 sameTimeInBeijing := time.Date(2009, 1, 1, 20, 0, 0, 0, beijing)
596
597
598
599 timesAreEqual := timeInUTC.Equal(sameTimeInBeijing)
600 fmt.Println(timesAreEqual)
601
602
603
604 }
605
606 func ExampleTime_Add() {
607 start := time.Date(2009, 1, 1, 12, 0, 0, 0, time.UTC)
608 afterTenSeconds := start.Add(time.Second * 10)
609 afterTenMinutes := start.Add(time.Minute * 10)
610 afterTenHours := start.Add(time.Hour * 10)
611 afterTenDays := start.Add(time.Hour * 24 * 10)
612
613 fmt.Printf("start = %v\n", start)
614 fmt.Printf("start.Add(time.Second * 10) = %v\n", afterTenSeconds)
615 fmt.Printf("start.Add(time.Minute * 10) = %v\n", afterTenMinutes)
616 fmt.Printf("start.Add(time.Hour * 10) = %v\n", afterTenHours)
617 fmt.Printf("start.Add(time.Hour * 24 * 10) = %v\n", afterTenDays)
618
619
620
621
622
623
624
625 }
626
627 func ExampleTime_AddDate() {
628 start := time.Date(2023, 03, 25, 12, 0, 0, 0, time.UTC)
629 oneDayLater := start.AddDate(0, 0, 1)
630 dayDuration := oneDayLater.Sub(start)
631 oneMonthLater := start.AddDate(0, 1, 0)
632 oneYearLater := start.AddDate(1, 0, 0)
633
634 zurich, err := time.LoadLocation("Europe/Zurich")
635 if err != nil {
636 panic(err)
637 }
638
639 startZurich := time.Date(2023, 03, 25, 12, 0, 0, 0, zurich)
640 oneDayLaterZurich := startZurich.AddDate(0, 0, 1)
641 dayDurationZurich := oneDayLaterZurich.Sub(startZurich)
642
643 fmt.Printf("oneDayLater: start.AddDate(0, 0, 1) = %v\n", oneDayLater)
644 fmt.Printf("oneMonthLater: start.AddDate(0, 1, 0) = %v\n", oneMonthLater)
645 fmt.Printf("oneYearLater: start.AddDate(1, 0, 0) = %v\n", oneYearLater)
646 fmt.Printf("oneDayLaterZurich: startZurich.AddDate(0, 0, 1) = %v\n", oneDayLaterZurich)
647 fmt.Printf("Day duration in UTC: %v | Day duration in Zürich: %v\n", dayDuration, dayDurationZurich)
648
649
650
651
652
653
654
655 }
656
657 func ExampleTime_After() {
658 year2000 := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
659 year3000 := time.Date(3000, 1, 1, 0, 0, 0, 0, time.UTC)
660
661 isYear3000AfterYear2000 := year3000.After(year2000)
662 isYear2000AfterYear3000 := year2000.After(year3000)
663
664 fmt.Printf("year3000.After(year2000) = %v\n", isYear3000AfterYear2000)
665 fmt.Printf("year2000.After(year3000) = %v\n", isYear2000AfterYear3000)
666
667
668
669
670 }
671
672 func ExampleTime_Before() {
673 year2000 := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
674 year3000 := time.Date(3000, 1, 1, 0, 0, 0, 0, time.UTC)
675
676 isYear2000BeforeYear3000 := year2000.Before(year3000)
677 isYear3000BeforeYear2000 := year3000.Before(year2000)
678
679 fmt.Printf("year2000.Before(year3000) = %v\n", isYear2000BeforeYear3000)
680 fmt.Printf("year3000.Before(year2000) = %v\n", isYear3000BeforeYear2000)
681
682
683
684
685 }
686
687 func ExampleTime_Date() {
688 d := time.Date(2000, 2, 1, 12, 30, 0, 0, time.UTC)
689 year, month, day := d.Date()
690
691 fmt.Printf("year = %v\n", year)
692 fmt.Printf("month = %v\n", month)
693 fmt.Printf("day = %v\n", day)
694
695
696
697
698
699 }
700
701 func ExampleTime_Day() {
702 d := time.Date(2000, 2, 1, 12, 30, 0, 0, time.UTC)
703 day := d.Day()
704
705 fmt.Printf("day = %v\n", day)
706
707
708
709 }
710
711 func ExampleTime_Equal() {
712 secondsEastOfUTC := int((8 * time.Hour).Seconds())
713 beijing := time.FixedZone("Beijing Time", secondsEastOfUTC)
714
715
716
717 d1 := time.Date(2000, 2, 1, 12, 30, 0, 0, time.UTC)
718 d2 := time.Date(2000, 2, 1, 20, 30, 0, 0, beijing)
719
720 datesEqualUsingEqualOperator := d1 == d2
721 datesEqualUsingFunction := d1.Equal(d2)
722
723 fmt.Printf("datesEqualUsingEqualOperator = %v\n", datesEqualUsingEqualOperator)
724 fmt.Printf("datesEqualUsingFunction = %v\n", datesEqualUsingFunction)
725
726
727
728
729 }
730
731 func ExampleTime_String() {
732 timeWithNanoseconds := time.Date(2000, 2, 1, 12, 13, 14, 15, time.UTC)
733 withNanoseconds := timeWithNanoseconds.String()
734
735 timeWithoutNanoseconds := time.Date(2000, 2, 1, 12, 13, 14, 0, time.UTC)
736 withoutNanoseconds := timeWithoutNanoseconds.String()
737
738 fmt.Printf("withNanoseconds = %v\n", string(withNanoseconds))
739 fmt.Printf("withoutNanoseconds = %v\n", string(withoutNanoseconds))
740
741
742
743
744 }
745
746 func ExampleTime_Sub() {
747 start := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
748 end := time.Date(2000, 1, 1, 12, 0, 0, 0, time.UTC)
749
750 difference := end.Sub(start)
751 fmt.Printf("difference = %v\n", difference)
752
753
754
755 }
756
757 func ExampleTime_AppendFormat() {
758 t := time.Date(2017, time.November, 4, 11, 0, 0, 0, time.UTC)
759 text := []byte("Time: ")
760
761 text = t.AppendFormat(text, time.Kitchen)
762 fmt.Println(string(text))
763
764
765
766 }
767
768 func ExampleFixedZone() {
769 loc := time.FixedZone("UTC-8", -8*60*60)
770 t := time.Date(2009, time.November, 10, 23, 0, 0, 0, loc)
771 fmt.Println("The time is:", t.Format(time.RFC822))
772
773 }
774
View as plain text