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