github.com/goproxy0/go@v0.0.0-20171111080102-49cc0c489d2c/src/time/example_test.go (about) 1 // Copyright 2011 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 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 // Output: 42 // d.Round( 1ns) = 1h15m30.918273645s 43 // d.Round( 1µs) = 1h15m30.918274s 44 // d.Round( 1ms) = 1h15m30.918s 45 // d.Round( 1s) = 1h15m31s 46 // d.Round( 2s) = 1h15m30s 47 // d.Round( 1m0s) = 1h16m0s 48 // d.Round( 10m0s) = 1h20m0s 49 // d.Round(1h0m0s) = 1h0m0s 50 } 51 52 func ExampleDuration_String() { 53 t1 := time.Date(2016, time.August, 15, 0, 0, 0, 0, time.UTC) 54 t2 := time.Date(2017, time.February, 16, 0, 0, 0, 0, time.UTC) 55 fmt.Println(t2.Sub(t1).String()) 56 // Output: 4440h0m0s 57 } 58 59 func ExampleDuration_Truncate() { 60 d, err := time.ParseDuration("1h15m30.918273645s") 61 if err != nil { 62 panic(err) 63 } 64 65 trunc := []time.Duration{ 66 time.Nanosecond, 67 time.Microsecond, 68 time.Millisecond, 69 time.Second, 70 2 * time.Second, 71 time.Minute, 72 10 * time.Minute, 73 time.Hour, 74 } 75 76 for _, t := range trunc { 77 fmt.Printf("t.Truncate(%6s) = %s\n", t, d.Truncate(t).String()) 78 } 79 // Output: 80 // t.Truncate( 1ns) = 1h15m30.918273645s 81 // t.Truncate( 1µs) = 1h15m30.918273s 82 // t.Truncate( 1ms) = 1h15m30.918s 83 // t.Truncate( 1s) = 1h15m30s 84 // t.Truncate( 2s) = 1h15m30s 85 // t.Truncate( 1m0s) = 1h15m0s 86 // t.Truncate( 10m0s) = 1h10m0s 87 // t.Truncate(1h0m0s) = 1h0m0s 88 } 89 90 func ExampleParseDuration() { 91 hours, _ := time.ParseDuration("10h") 92 complex, _ := time.ParseDuration("1h10m10s") 93 94 fmt.Println(hours) 95 fmt.Println(complex) 96 fmt.Printf("there are %.0f seconds in %v\n", complex.Seconds(), complex) 97 // Output: 98 // 10h0m0s 99 // 1h10m10s 100 // there are 4210 seconds in 1h10m10s 101 } 102 103 func ExampleDuration_Hours() { 104 h, _ := time.ParseDuration("4h30m") 105 fmt.Printf("I've got %.1f hours of work left.", h.Hours()) 106 // Output: I've got 4.5 hours of work left. 107 } 108 109 func ExampleDuration_Minutes() { 110 m, _ := time.ParseDuration("1h30m") 111 fmt.Printf("The movie is %.0f minutes long.", m.Minutes()) 112 // Output: The movie is 90 minutes long. 113 } 114 115 func ExampleDuration_Nanoseconds() { 116 ns, _ := time.ParseDuration("1000ns") 117 fmt.Printf("one microsecond has %d nanoseconds.", ns.Nanoseconds()) 118 // Output: one microsecond has 1000 nanoseconds. 119 } 120 121 func ExampleDuration_Seconds() { 122 m, _ := time.ParseDuration("1m30s") 123 fmt.Printf("take off in t-%.0f seconds.", m.Seconds()) 124 // Output: take off in t-90 seconds. 125 } 126 127 var c chan int 128 129 func handle(int) {} 130 131 func ExampleAfter() { 132 select { 133 case m := <-c: 134 handle(m) 135 case <-time.After(5 * time.Minute): 136 fmt.Println("timed out") 137 } 138 } 139 140 func ExampleSleep() { 141 time.Sleep(100 * time.Millisecond) 142 } 143 144 func statusUpdate() string { return "" } 145 146 func ExampleTick() { 147 c := time.Tick(1 * time.Minute) 148 for now := range c { 149 fmt.Printf("%v %s\n", now, statusUpdate()) 150 } 151 } 152 153 func ExampleMonth() { 154 _, month, day := time.Now().Date() 155 if month == time.November && day == 10 { 156 fmt.Println("Happy Go day!") 157 } 158 } 159 160 func ExampleDate() { 161 t := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC) 162 fmt.Printf("Go launched at %s\n", t.Local()) 163 // Output: Go launched at 2009-11-10 15:00:00 -0800 PST 164 } 165 166 func ExampleNewTicker() { 167 ticker := time.NewTicker(time.Second) 168 defer ticker.Stop() 169 done := make(chan bool) 170 go func() { 171 time.Sleep(10 * time.Second) 172 done <- true 173 }() 174 for { 175 select { 176 case <-done: 177 fmt.Println("Done!") 178 return 179 case t := <-ticker.C: 180 fmt.Println("Current time: ", t) 181 } 182 } 183 } 184 185 func ExampleTime_Format() { 186 // Parse a time value from a string in the standard Unix format. 187 t, err := time.Parse(time.UnixDate, "Sat Mar 7 11:06:39 PST 2015") 188 if err != nil { // Always check errors even if they should not happen. 189 panic(err) 190 } 191 192 // time.Time's Stringer method is useful without any format. 193 fmt.Println("default format:", t) 194 195 // Predefined constants in the package implement common layouts. 196 fmt.Println("Unix format:", t.Format(time.UnixDate)) 197 198 // The time zone attached to the time value affects its output. 199 fmt.Println("Same, in UTC:", t.UTC().Format(time.UnixDate)) 200 201 // The rest of this function demonstrates the properties of the 202 // layout string used in the format. 203 204 // The layout string used by the Parse function and Format method 205 // shows by example how the reference time should be represented. 206 // We stress that one must show how the reference time is formatted, 207 // not a time of the user's choosing. Thus each layout string is a 208 // representation of the time stamp, 209 // Jan 2 15:04:05 2006 MST 210 // An easy way to remember this value is that it holds, when presented 211 // in this order, the values (lined up with the elements above): 212 // 1 2 3 4 5 6 -7 213 // There are some wrinkles illustrated below. 214 215 // Most uses of Format and Parse use constant layout strings such as 216 // the ones defined in this package, but the interface is flexible, 217 // as these examples show. 218 219 // Define a helper function to make the examples' output look nice. 220 do := func(name, layout, want string) { 221 got := t.Format(layout) 222 if want != got { 223 fmt.Printf("error: for %q got %q; expected %q\n", layout, got, want) 224 return 225 } 226 fmt.Printf("%-15s %q gives %q\n", name, layout, got) 227 } 228 229 // Print a header in our output. 230 fmt.Printf("\nFormats:\n\n") 231 232 // A simple starter example. 233 do("Basic", "Mon Jan 2 15:04:05 MST 2006", "Sat Mar 7 11:06:39 PST 2015") 234 235 // For fixed-width printing of values, such as the date, that may be one or 236 // two characters (7 vs. 07), use an _ instead of a space in the layout string. 237 // Here we print just the day, which is 2 in our layout string and 7 in our 238 // value. 239 do("No pad", "<2>", "<7>") 240 241 // An underscore represents a space pad, if the date only has one digit. 242 do("Spaces", "<_2>", "< 7>") 243 244 // A "0" indicates zero padding for single-digit values. 245 do("Zeros", "<02>", "<07>") 246 247 // If the value is already the right width, padding is not used. 248 // For instance, the second (05 in the reference time) in our value is 39, 249 // so it doesn't need padding, but the minutes (04, 06) does. 250 do("Suppressed pad", "04:05", "06:39") 251 252 // The predefined constant Unix uses an underscore to pad the day. 253 // Compare with our simple starter example. 254 do("Unix", time.UnixDate, "Sat Mar 7 11:06:39 PST 2015") 255 256 // The hour of the reference time is 15, or 3PM. The layout can express 257 // it either way, and since our value is the morning we should see it as 258 // an AM time. We show both in one format string. Lower case too. 259 do("AM/PM", "3PM==3pm==15h", "11AM==11am==11h") 260 261 // When parsing, if the seconds value is followed by a decimal point 262 // and some digits, that is taken as a fraction of a second even if 263 // the layout string does not represent the fractional second. 264 // Here we add a fractional second to our time value used above. 265 t, err = time.Parse(time.UnixDate, "Sat Mar 7 11:06:39.1234 PST 2015") 266 if err != nil { 267 panic(err) 268 } 269 // It does not appear in the output if the layout string does not contain 270 // a representation of the fractional second. 271 do("No fraction", time.UnixDate, "Sat Mar 7 11:06:39 PST 2015") 272 273 // Fractional seconds can be printed by adding a run of 0s or 9s after 274 // a decimal point in the seconds value in the layout string. 275 // If the layout digits are 0s, the fractional second is of the specified 276 // width. Note that the output has a trailing zero. 277 do("0s for fraction", "15:04:05.00000", "11:06:39.12340") 278 279 // If the fraction in the layout is 9s, trailing zeros are dropped. 280 do("9s for fraction", "15:04:05.99999999", "11:06:39.1234") 281 282 // Output: 283 // default format: 2015-03-07 11:06:39 -0800 PST 284 // Unix format: Sat Mar 7 11:06:39 PST 2015 285 // Same, in UTC: Sat Mar 7 19:06:39 UTC 2015 286 // 287 // Formats: 288 // 289 // Basic "Mon Jan 2 15:04:05 MST 2006" gives "Sat Mar 7 11:06:39 PST 2015" 290 // No pad "<2>" gives "<7>" 291 // Spaces "<_2>" gives "< 7>" 292 // Zeros "<02>" gives "<07>" 293 // Suppressed pad "04:05" gives "06:39" 294 // Unix "Mon Jan _2 15:04:05 MST 2006" gives "Sat Mar 7 11:06:39 PST 2015" 295 // AM/PM "3PM==3pm==15h" gives "11AM==11am==11h" 296 // No fraction "Mon Jan _2 15:04:05 MST 2006" gives "Sat Mar 7 11:06:39 PST 2015" 297 // 0s for fraction "15:04:05.00000" gives "11:06:39.12340" 298 // 9s for fraction "15:04:05.99999999" gives "11:06:39.1234" 299 300 } 301 302 func ExampleParse() { 303 // See the example for Time.Format for a thorough description of how 304 // to define the layout string to parse a time.Time value; Parse and 305 // Format use the same model to describe their input and output. 306 307 // longForm shows by example how the reference time would be represented in 308 // the desired layout. 309 const longForm = "Jan 2, 2006 at 3:04pm (MST)" 310 t, _ := time.Parse(longForm, "Feb 3, 2013 at 7:54pm (PST)") 311 fmt.Println(t) 312 313 // shortForm is another way the reference time would be represented 314 // in the desired layout; it has no time zone present. 315 // Note: without explicit zone, returns time in UTC. 316 const shortForm = "2006-Jan-02" 317 t, _ = time.Parse(shortForm, "2013-Feb-03") 318 fmt.Println(t) 319 320 // Some valid layouts are invalid time values, due to format specifiers 321 // such as _ for space padding and Z for zone information. 322 // For example the RFC3339 layout 2006-01-02T15:04:05Z07:00 323 // contains both Z and a time zone offset in order to handle both valid options: 324 // 2006-01-02T15:04:05Z 325 // 2006-01-02T15:04:05+07:00 326 t, _ = time.Parse(time.RFC3339, "2006-01-02T15:04:05Z") 327 fmt.Println(t) 328 t, _ = time.Parse(time.RFC3339, "2006-01-02T15:04:05+07:00") 329 fmt.Println(t) 330 _, err := time.Parse(time.RFC3339, time.RFC3339) 331 fmt.Println("error", err) // Returns an error as the layout is not a valid time value 332 333 // Output: 334 // 2013-02-03 19:54:00 -0800 PST 335 // 2013-02-03 00:00:00 +0000 UTC 336 // 2006-01-02 15:04:05 +0000 UTC 337 // 2006-01-02 15:04:05 +0700 +0700 338 // error parsing time "2006-01-02T15:04:05Z07:00": extra text: 07:00 339 } 340 341 func ExampleParseInLocation() { 342 loc, _ := time.LoadLocation("Europe/Berlin") 343 344 const longForm = "Jan 2, 2006 at 3:04pm (MST)" 345 t, _ := time.ParseInLocation(longForm, "Jul 9, 2012 at 5:02am (CEST)", loc) 346 fmt.Println(t) 347 348 // Note: without explicit zone, returns time in given location. 349 const shortForm = "2006-Jan-02" 350 t, _ = time.ParseInLocation(shortForm, "2012-Jul-09", loc) 351 fmt.Println(t) 352 353 // Output: 354 // 2012-07-09 05:02:00 +0200 CEST 355 // 2012-07-09 00:00:00 +0200 CEST 356 } 357 358 func ExampleTime_Round() { 359 t := time.Date(0, 0, 0, 12, 15, 30, 918273645, time.UTC) 360 round := []time.Duration{ 361 time.Nanosecond, 362 time.Microsecond, 363 time.Millisecond, 364 time.Second, 365 2 * time.Second, 366 time.Minute, 367 10 * time.Minute, 368 time.Hour, 369 } 370 371 for _, d := range round { 372 fmt.Printf("t.Round(%6s) = %s\n", d, t.Round(d).Format("15:04:05.999999999")) 373 } 374 // Output: 375 // t.Round( 1ns) = 12:15:30.918273645 376 // t.Round( 1µs) = 12:15:30.918274 377 // t.Round( 1ms) = 12:15:30.918 378 // t.Round( 1s) = 12:15:31 379 // t.Round( 2s) = 12:15:30 380 // t.Round( 1m0s) = 12:16:00 381 // t.Round( 10m0s) = 12:20:00 382 // t.Round(1h0m0s) = 12:00:00 383 } 384 385 func ExampleTime_Truncate() { 386 t, _ := time.Parse("2006 Jan 02 15:04:05", "2012 Dec 07 12:15:30.918273645") 387 trunc := []time.Duration{ 388 time.Nanosecond, 389 time.Microsecond, 390 time.Millisecond, 391 time.Second, 392 2 * time.Second, 393 time.Minute, 394 10 * time.Minute, 395 } 396 397 for _, d := range trunc { 398 fmt.Printf("t.Truncate(%5s) = %s\n", d, t.Truncate(d).Format("15:04:05.999999999")) 399 } 400 // To round to the last midnight in the local timezone, create a new Date. 401 midnight := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.Local) 402 _ = midnight 403 404 // Output: 405 // t.Truncate( 1ns) = 12:15:30.918273645 406 // t.Truncate( 1µs) = 12:15:30.918273 407 // t.Truncate( 1ms) = 12:15:30.918 408 // t.Truncate( 1s) = 12:15:30 409 // t.Truncate( 2s) = 12:15:30 410 // t.Truncate( 1m0s) = 12:15:00 411 // t.Truncate(10m0s) = 12:10:00 412 } 413 414 func ExampleLocation() { 415 // China doesn't have daylight saving. It uses a fixed 8 hour offset from UTC. 416 secondsEastOfUTC := int((8 * time.Hour).Seconds()) 417 beijing := time.FixedZone("Beijing Time", secondsEastOfUTC) 418 419 // If the system has a timezone database present, it's possible to load a location 420 // from that, e.g.: 421 // newYork, err := time.LoadLocation("America/New_York") 422 423 // Creating a time requires a location. Common locations are time.Local and time.UTC. 424 timeInUTC := time.Date(2009, 1, 1, 12, 0, 0, 0, time.UTC) 425 sameTimeInBeijing := time.Date(2009, 1, 1, 20, 0, 0, 0, beijing) 426 427 // Although the UTC clock time is 1200 and the Beijing clock time is 2000, Beijing is 428 // 8 hours ahead so the two dates actually represent the same instant. 429 timesAreEqual := timeInUTC.Equal(sameTimeInBeijing) 430 fmt.Println(timesAreEqual) 431 432 // Output: 433 // true 434 } 435 436 func ExampleTime_Add() { 437 start := time.Date(2009, 1, 1, 12, 0, 0, 0, time.UTC) 438 afterTenSeconds := start.Add(time.Second * 10) 439 afterTenMinutes := start.Add(time.Minute * 10) 440 afterTenHours := start.Add(time.Hour * 10) 441 afterTenDays := start.Add(time.Hour * 24 * 10) 442 443 fmt.Printf("start = %v\n", start) 444 fmt.Printf("start.Add(time.Second * 10) = %v\n", afterTenSeconds) 445 fmt.Printf("start.Add(time.Minute * 10) = %v\n", afterTenMinutes) 446 fmt.Printf("start.Add(time.Hour * 10) = %v\n", afterTenHours) 447 fmt.Printf("start.Add(time.Hour * 24 * 10) = %v\n", afterTenDays) 448 449 // Output: 450 // start = 2009-01-01 12:00:00 +0000 UTC 451 // start.Add(time.Second * 10) = 2009-01-01 12:00:10 +0000 UTC 452 // start.Add(time.Minute * 10) = 2009-01-01 12:10:00 +0000 UTC 453 // start.Add(time.Hour * 10) = 2009-01-01 22:00:00 +0000 UTC 454 // start.Add(time.Hour * 24 * 10) = 2009-01-11 12:00:00 +0000 UTC 455 } 456 457 func ExampleTime_AddDate() { 458 start := time.Date(2009, 1, 1, 0, 0, 0, 0, time.UTC) 459 oneDayLater := start.AddDate(0, 0, 1) 460 oneMonthLater := start.AddDate(0, 1, 0) 461 oneYearLater := start.AddDate(1, 0, 0) 462 463 fmt.Printf("oneDayLater: start.AddDate(0, 0, 1) = %v\n", oneDayLater) 464 fmt.Printf("oneMonthLater: start.AddDate(0, 1, 0) = %v\n", oneMonthLater) 465 fmt.Printf("oneYearLater: start.AddDate(1, 0, 0) = %v\n", oneYearLater) 466 467 // Output: 468 // oneDayLater: start.AddDate(0, 0, 1) = 2009-01-02 00:00:00 +0000 UTC 469 // oneMonthLater: start.AddDate(0, 1, 0) = 2009-02-01 00:00:00 +0000 UTC 470 // oneYearLater: start.AddDate(1, 0, 0) = 2010-01-01 00:00:00 +0000 UTC 471 } 472 473 func ExampleTime_After() { 474 year2000 := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC) 475 year3000 := time.Date(3000, 1, 1, 0, 0, 0, 0, time.UTC) 476 477 isYear3000AfterYear2000 := year3000.After(year2000) // True 478 isYear2000AfterYear3000 := year2000.After(year3000) // False 479 480 fmt.Printf("year3000.After(year2000) = %v\n", isYear3000AfterYear2000) 481 fmt.Printf("year2000.After(year3000) = %v\n", isYear2000AfterYear3000) 482 483 // Output: 484 // year3000.After(year2000) = true 485 // year2000.After(year3000) = false 486 } 487 488 func ExampleTime_Before() { 489 year2000 := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC) 490 year3000 := time.Date(3000, 1, 1, 0, 0, 0, 0, time.UTC) 491 492 isYear2000BeforeYear3000 := year2000.Before(year3000) // True 493 isYear3000BeforeYear2000 := year3000.Before(year2000) // False 494 495 fmt.Printf("year2000.Before(year3000) = %v\n", isYear2000BeforeYear3000) 496 fmt.Printf("year3000.Before(year2000) = %v\n", isYear3000BeforeYear2000) 497 498 // Output: 499 // year2000.Before(year3000) = true 500 // year3000.Before(year2000) = false 501 } 502 503 func ExampleTime_Date() { 504 d := time.Date(2000, 2, 1, 12, 30, 0, 0, time.UTC) 505 year, month, day := d.Date() 506 507 fmt.Printf("year = %v\n", year) 508 fmt.Printf("month = %v\n", month) 509 fmt.Printf("day = %v\n", day) 510 511 // Output: 512 // year = 2000 513 // month = February 514 // day = 1 515 } 516 517 func ExampleTime_Day() { 518 d := time.Date(2000, 2, 1, 12, 30, 0, 0, time.UTC) 519 day := d.Day() 520 521 fmt.Printf("day = %v\n", day) 522 523 // Output: 524 // day = 1 525 } 526 527 func ExampleTime_Equal() { 528 secondsEastOfUTC := int((8 * time.Hour).Seconds()) 529 beijing := time.FixedZone("Beijing Time", secondsEastOfUTC) 530 531 // Unlike the equal operator, Equal is aware that d1 and d2 are the 532 // same instant but in different time zones. 533 d1 := time.Date(2000, 2, 1, 12, 30, 0, 0, time.UTC) 534 d2 := time.Date(2000, 2, 1, 20, 30, 0, 0, beijing) 535 536 datesEqualUsingEqualOperator := d1 == d2 537 datesEqualUsingFunction := d1.Equal(d2) 538 539 fmt.Printf("datesEqualUsingEqualOperator = %v\n", datesEqualUsingEqualOperator) 540 fmt.Printf("datesEqualUsingFunction = %v\n", datesEqualUsingFunction) 541 542 // Output: 543 // datesEqualUsingEqualOperator = false 544 // datesEqualUsingFunction = true 545 } 546 547 func ExampleTime_String() { 548 timeWithNanoseconds := time.Date(2000, 2, 1, 12, 13, 14, 15, time.UTC) 549 withNanoseconds := timeWithNanoseconds.String() 550 551 timeWithoutNanoseconds := time.Date(2000, 2, 1, 12, 13, 14, 0, time.UTC) 552 withoutNanoseconds := timeWithoutNanoseconds.String() 553 554 fmt.Printf("withNanoseconds = %v\n", string(withNanoseconds)) 555 fmt.Printf("withoutNanoseconds = %v\n", string(withoutNanoseconds)) 556 557 // Output: 558 // withNanoseconds = 2000-02-01 12:13:14.000000015 +0000 UTC 559 // withoutNanoseconds = 2000-02-01 12:13:14 +0000 UTC 560 } 561 562 func ExampleTime_Sub() { 563 start := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC) 564 end := time.Date(2000, 1, 1, 12, 0, 0, 0, time.UTC) 565 566 difference := end.Sub(start) 567 fmt.Printf("difference = %v\n", difference) 568 569 // Output: 570 // difference = 12h0m0s 571 } 572 573 func ExampleTime_AppendFormat() { 574 t := time.Date(2017, time.November, 4, 11, 0, 0, 0, time.UTC) 575 text := []byte("Time: ") 576 577 text = t.AppendFormat(text, time.Kitchen) 578 fmt.Println(string(text)) 579 580 // Output: 581 // Time: 11:00AM 582 }