Black Lives Matter. Support the Equal Justice Initiative.

Source file src/time/example_test.go

Documentation: time

     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  	fmt.Println(1*time.Hour + 2*time.Minute + 300*time.Millisecond)
    54  	fmt.Println(300 * time.Millisecond)
    55  	// Output:
    56  	// 1h2m0.3s
    57  	// 300ms
    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  	// Output:
    81  	// d.Truncate(   1ns) = 1h15m30.918273645s
    82  	// d.Truncate(   1µs) = 1h15m30.918273s
    83  	// d.Truncate(   1ms) = 1h15m30.918s
    84  	// d.Truncate(    1s) = 1h15m30s
    85  	// d.Truncate(    2s) = 1h15m30s
    86  	// d.Truncate(  1m0s) = 1h15m0s
    87  	// d.Truncate( 10m0s) = 1h10m0s
    88  	// d.Truncate(1h0m0s) = 1h0m0s
    89  }
    90  
    91  func ExampleParseDuration() {
    92  	hours, _ := time.ParseDuration("10h")
    93  	complex, _ := time.ParseDuration("1h10m10s")
    94  	micro, _ := time.ParseDuration("1µs")
    95  	// The package also accepts the incorrect but common prefix u for micro.
    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(), micro)
   103  	// Output:
   104  	// 10h0m0s
   105  	// 1h10m10s
   106  	// There are 4210 seconds in 1h10m10s.
   107  	// There are 1000 nanoseconds in 1µs.
   108  	// There are 1.00e-06 seconds in 1µs.
   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  	// Output: I've got 4.5 hours of work left.
   115  }
   116  
   117  func ExampleDuration_Microseconds() {
   118  	u, _ := time.ParseDuration("1s")
   119  	fmt.Printf("One second is %d microseconds.\n", u.Microseconds())
   120  	// Output:
   121  	// One second is 1000000 microseconds.
   122  }
   123  
   124  func ExampleDuration_Milliseconds() {
   125  	u, _ := time.ParseDuration("1s")
   126  	fmt.Printf("One second is %d milliseconds.\n", u.Milliseconds())
   127  	// Output:
   128  	// One second is 1000 milliseconds.
   129  }
   130  
   131  func ExampleDuration_Minutes() {
   132  	m, _ := time.ParseDuration("1h30m")
   133  	fmt.Printf("The movie is %.0f minutes long.", m.Minutes())
   134  	// Output: The movie is 90 minutes long.
   135  }
   136  
   137  func ExampleDuration_Nanoseconds() {
   138  	u, _ := time.ParseDuration("1µs")
   139  	fmt.Printf("One microsecond is %d nanoseconds.\n", u.Nanoseconds())
   140  	// Output:
   141  	// One microsecond is 1000 nanoseconds.
   142  }
   143  
   144  func ExampleDuration_Seconds() {
   145  	m, _ := time.ParseDuration("1m30s")
   146  	fmt.Printf("Take off in t-%.0f seconds.", m.Seconds())
   147  	// Output: Take off in t-90 seconds.
   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  	// Output: Go launched at 2009-11-10 15:00:00 -0800 PST
   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  	// Parse a time value from a string in the standard Unix format.
   210  	t, err := time.Parse(time.UnixDate, "Wed Feb 25 11:06:39 PST 2015")
   211  	if err != nil { // Always check errors even if they should not happen.
   212  		panic(err)
   213  	}
   214  
   215  	// time.Time's Stringer method is useful without any format.
   216  	fmt.Println("default format:", t)
   217  
   218  	// Predefined constants in the package implement common layouts.
   219  	fmt.Println("Unix format:", t.Format(time.UnixDate))
   220  
   221  	// The time zone attached to the time value affects its output.
   222  	fmt.Println("Same, in UTC:", t.UTC().Format(time.UnixDate))
   223  
   224  	// The rest of this function demonstrates the properties of the
   225  	// layout string used in the format.
   226  
   227  	// The layout string used by the Parse function and Format method
   228  	// shows by example how the reference time should be represented.
   229  	// We stress that one must show how the reference time is formatted,
   230  	// not a time of the user's choosing. Thus each layout string is a
   231  	// representation of the time stamp,
   232  	//	Jan 2 15:04:05 2006 MST
   233  	// An easy way to remember this value is that it holds, when presented
   234  	// in this order, the values (lined up with the elements above):
   235  	//	  1 2  3  4  5    6  -7
   236  	// There are some wrinkles illustrated below.
   237  
   238  	// Most uses of Format and Parse use constant layout strings such as
   239  	// the ones defined in this package, but the interface is flexible,
   240  	// as these examples show.
   241  
   242  	// Define a helper function to make the examples' output look nice.
   243  	do := func(name, layout, want string) {
   244  		got := t.Format(layout)
   245  		if want != got {
   246  			fmt.Printf("error: for %q got %q; expected %q\n", layout, got, want)
   247  			return
   248  		}
   249  		fmt.Printf("%-16s %q gives %q\n", name, layout, got)
   250  	}
   251  
   252  	// Print a header in our output.
   253  	fmt.Printf("\nFormats:\n\n")
   254  
   255  	// Simple starter examples.
   256  	do("Basic full date", "Mon Jan 2 15:04:05 MST 2006", "Wed Feb 25 11:06:39 PST 2015")
   257  	do("Basic short date", "2006/01/02", "2015/02/25")
   258  
   259  	// The hour of the reference time is 15, or 3PM. The layout can express
   260  	// it either way, and since our value is the morning we should see it as
   261  	// an AM time. We show both in one format string. Lower case too.
   262  	do("AM/PM", "3PM==3pm==15h", "11AM==11am==11h")
   263  
   264  	// When parsing, if the seconds value is followed by a decimal point
   265  	// and some digits, that is taken as a fraction of a second even if
   266  	// the layout string does not represent the fractional second.
   267  	// Here we add a fractional second to our time value used above.
   268  	t, err = time.Parse(time.UnixDate, "Wed Feb 25 11:06:39.1234 PST 2015")
   269  	if err != nil {
   270  		panic(err)
   271  	}
   272  	// It does not appear in the output if the layout string does not contain
   273  	// a representation of the fractional second.
   274  	do("No fraction", time.UnixDate, "Wed Feb 25 11:06:39 PST 2015")
   275  
   276  	// Fractional seconds can be printed by adding a run of 0s or 9s after
   277  	// a decimal point in the seconds value in the layout string.
   278  	// If the layout digits are 0s, the fractional second is of the specified
   279  	// width. Note that the output has a trailing zero.
   280  	do("0s for fraction", "15:04:05.00000", "11:06:39.12340")
   281  
   282  	// If the fraction in the layout is 9s, trailing zeros are dropped.
   283  	do("9s for fraction", "15:04:05.99999999", "11:06:39.1234")
   284  
   285  	// Output:
   286  	// default format: 2015-02-25 11:06:39 -0800 PST
   287  	// Unix format: Wed Feb 25 11:06:39 PST 2015
   288  	// Same, in UTC: Wed Feb 25 19:06:39 UTC 2015
   289  	//
   290  	// Formats:
   291  	//
   292  	// Basic full date  "Mon Jan 2 15:04:05 MST 2006" gives "Wed Feb 25 11:06:39 PST 2015"
   293  	// Basic short date "2006/01/02" gives "2015/02/25"
   294  	// AM/PM            "3PM==3pm==15h" gives "11AM==11am==11h"
   295  	// No fraction      "Mon Jan _2 15:04:05 MST 2006" gives "Wed Feb 25 11:06:39 PST 2015"
   296  	// 0s for fraction  "15:04:05.00000" gives "11:06:39.12340"
   297  	// 9s for fraction  "15:04:05.99999999" gives "11:06:39.1234"
   298  
   299  }
   300  
   301  func ExampleTime_Format_pad() {
   302  	// Parse a time value from a string in the standard Unix format.
   303  	t, err := time.Parse(time.UnixDate, "Sat Mar 7 11:06:39 PST 2015")
   304  	if err != nil { // Always check errors even if they should not happen.
   305  		panic(err)
   306  	}
   307  
   308  	// Define a helper function to make the examples' output look nice.
   309  	do := func(name, layout, want string) {
   310  		got := t.Format(layout)
   311  		if want != got {
   312  			fmt.Printf("error: for %q got %q; expected %q\n", layout, got, want)
   313  			return
   314  		}
   315  		fmt.Printf("%-16s %q gives %q\n", name, layout, got)
   316  	}
   317  
   318  	// The predefined constant Unix uses an underscore to pad the day.
   319  	do("Unix", time.UnixDate, "Sat Mar  7 11:06:39 PST 2015")
   320  
   321  	// For fixed-width printing of values, such as the date, that may be one or
   322  	// two characters (7 vs. 07), use an _ instead of a space in the layout string.
   323  	// Here we print just the day, which is 2 in our layout string and 7 in our
   324  	// value.
   325  	do("No pad", "<2>", "<7>")
   326  
   327  	// An underscore represents a space pad, if the date only has one digit.
   328  	do("Spaces", "<_2>", "< 7>")
   329  
   330  	// A "0" indicates zero padding for single-digit values.
   331  	do("Zeros", "<02>", "<07>")
   332  
   333  	// If the value is already the right width, padding is not used.
   334  	// For instance, the second (05 in the reference time) in our value is 39,
   335  	// so it doesn't need padding, but the minutes (04, 06) does.
   336  	do("Suppressed pad", "04:05", "06:39")
   337  
   338  	// Output:
   339  	// Unix             "Mon Jan _2 15:04:05 MST 2006" gives "Sat Mar  7 11:06:39 PST 2015"
   340  	// No pad           "<2>" gives "<7>"
   341  	// Spaces           "<_2>" gives "< 7>"
   342  	// Zeros            "<02>" gives "<07>"
   343  	// Suppressed pad   "04:05" gives "06:39"
   344  
   345  }
   346  
   347  func ExampleParse() {
   348  	// See the example for Time.Format for a thorough description of how
   349  	// to define the layout string to parse a time.Time value; Parse and
   350  	// Format use the same model to describe their input and output.
   351  
   352  	// longForm shows by example how the reference time would be represented in
   353  	// the desired layout.
   354  	const longForm = "Jan 2, 2006 at 3:04pm (MST)"
   355  	t, _ := time.Parse(longForm, "Feb 3, 2013 at 7:54pm (PST)")
   356  	fmt.Println(t)
   357  
   358  	// shortForm is another way the reference time would be represented
   359  	// in the desired layout; it has no time zone present.
   360  	// Note: without explicit zone, returns time in UTC.
   361  	const shortForm = "2006-Jan-02"
   362  	t, _ = time.Parse(shortForm, "2013-Feb-03")
   363  	fmt.Println(t)
   364  
   365  	// Some valid layouts are invalid time values, due to format specifiers
   366  	// such as _ for space padding and Z for zone information.
   367  	// For example the RFC3339 layout 2006-01-02T15:04:05Z07:00
   368  	// contains both Z and a time zone offset in order to handle both valid options:
   369  	// 2006-01-02T15:04:05Z
   370  	// 2006-01-02T15:04:05+07:00
   371  	t, _ = time.Parse(time.RFC3339, "2006-01-02T15:04:05Z")
   372  	fmt.Println(t)
   373  	t, _ = time.Parse(time.RFC3339, "2006-01-02T15:04:05+07:00")
   374  	fmt.Println(t)
   375  	_, err := time.Parse(time.RFC3339, time.RFC3339)
   376  	fmt.Println("error", err) // Returns an error as the layout is not a valid time value
   377  
   378  	// Output:
   379  	// 2013-02-03 19:54:00 -0800 PST
   380  	// 2013-02-03 00:00:00 +0000 UTC
   381  	// 2006-01-02 15:04:05 +0000 UTC
   382  	// 2006-01-02 15:04:05 +0700 +0700
   383  	// error parsing time "2006-01-02T15:04:05Z07:00": extra text: "07:00"
   384  }
   385  
   386  func ExampleParseInLocation() {
   387  	loc, _ := time.LoadLocation("Europe/Berlin")
   388  
   389  	// This will look for the name CEST in the Europe/Berlin time zone.
   390  	const longForm = "Jan 2, 2006 at 3:04pm (MST)"
   391  	t, _ := time.ParseInLocation(longForm, "Jul 9, 2012 at 5:02am (CEST)", loc)
   392  	fmt.Println(t)
   393  
   394  	// Note: without explicit zone, returns time in given location.
   395  	const shortForm = "2006-Jan-02"
   396  	t, _ = time.ParseInLocation(shortForm, "2012-Jul-09", loc)
   397  	fmt.Println(t)
   398  
   399  	// Output:
   400  	// 2012-07-09 05:02:00 +0200 CEST
   401  	// 2012-07-09 00:00:00 +0200 CEST
   402  }
   403  
   404  func ExampleTime_Unix() {
   405  	// 1 billion seconds of Unix, three ways.
   406  	fmt.Println(time.Unix(1e9, 0).UTC())     // 1e9 seconds
   407  	fmt.Println(time.Unix(0, 1e18).UTC())    // 1e18 nanoseconds
   408  	fmt.Println(time.Unix(2e9, -1e18).UTC()) // 2e9 seconds - 1e18 nanoseconds
   409  
   410  	t := time.Date(2001, time.September, 9, 1, 46, 40, 0, time.UTC)
   411  	fmt.Println(t.Unix())     // seconds since 1970
   412  	fmt.Println(t.UnixNano()) // nanoseconds since 1970
   413  
   414  	// Output:
   415  	// 2001-09-09 01:46:40 +0000 UTC
   416  	// 2001-09-09 01:46:40 +0000 UTC
   417  	// 2001-09-09 01:46:40 +0000 UTC
   418  	// 1000000000
   419  	// 1000000000000000000
   420  }
   421  
   422  func ExampleTime_Round() {
   423  	t := time.Date(0, 0, 0, 12, 15, 30, 918273645, time.UTC)
   424  	round := []time.Duration{
   425  		time.Nanosecond,
   426  		time.Microsecond,
   427  		time.Millisecond,
   428  		time.Second,
   429  		2 * time.Second,
   430  		time.Minute,
   431  		10 * time.Minute,
   432  		time.Hour,
   433  	}
   434  
   435  	for _, d := range round {
   436  		fmt.Printf("t.Round(%6s) = %s\n", d, t.Round(d).Format("15:04:05.999999999"))
   437  	}
   438  	// Output:
   439  	// t.Round(   1ns) = 12:15:30.918273645
   440  	// t.Round(   1µs) = 12:15:30.918274
   441  	// t.Round(   1ms) = 12:15:30.918
   442  	// t.Round(    1s) = 12:15:31
   443  	// t.Round(    2s) = 12:15:30
   444  	// t.Round(  1m0s) = 12:16:00
   445  	// t.Round( 10m0s) = 12:20:00
   446  	// t.Round(1h0m0s) = 12:00:00
   447  }
   448  
   449  func ExampleTime_Truncate() {
   450  	t, _ := time.Parse("2006 Jan 02 15:04:05", "2012 Dec 07 12:15:30.918273645")
   451  	trunc := []time.Duration{
   452  		time.Nanosecond,
   453  		time.Microsecond,
   454  		time.Millisecond,
   455  		time.Second,
   456  		2 * time.Second,
   457  		time.Minute,
   458  		10 * time.Minute,
   459  	}
   460  
   461  	for _, d := range trunc {
   462  		fmt.Printf("t.Truncate(%5s) = %s\n", d, t.Truncate(d).Format("15:04:05.999999999"))
   463  	}
   464  	// To round to the last midnight in the local timezone, create a new Date.
   465  	midnight := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.Local)
   466  	_ = midnight
   467  
   468  	// Output:
   469  	// t.Truncate(  1ns) = 12:15:30.918273645
   470  	// t.Truncate(  1µs) = 12:15:30.918273
   471  	// t.Truncate(  1ms) = 12:15:30.918
   472  	// t.Truncate(   1s) = 12:15:30
   473  	// t.Truncate(   2s) = 12:15:30
   474  	// t.Truncate( 1m0s) = 12:15:00
   475  	// t.Truncate(10m0s) = 12:10:00
   476  }
   477  
   478  func ExampleLoadLocation() {
   479  	location, err := time.LoadLocation("America/Los_Angeles")
   480  	if err != nil {
   481  		panic(err)
   482  	}
   483  
   484  	timeInUTC := time.Date(2018, 8, 30, 12, 0, 0, 0, time.UTC)
   485  	fmt.Println(timeInUTC.In(location))
   486  	// Output: 2018-08-30 05:00:00 -0700 PDT
   487  }
   488  
   489  func ExampleLocation() {
   490  	// China doesn't have daylight saving. It uses a fixed 8 hour offset from UTC.
   491  	secondsEastOfUTC := int((8 * time.Hour).Seconds())
   492  	beijing := time.FixedZone("Beijing Time", secondsEastOfUTC)
   493  
   494  	// If the system has a timezone database present, it's possible to load a location
   495  	// from that, e.g.:
   496  	//    newYork, err := time.LoadLocation("America/New_York")
   497  
   498  	// Creating a time requires a location. Common locations are time.Local and time.UTC.
   499  	timeInUTC := time.Date(2009, 1, 1, 12, 0, 0, 0, time.UTC)
   500  	sameTimeInBeijing := time.Date(2009, 1, 1, 20, 0, 0, 0, beijing)
   501  
   502  	// Although the UTC clock time is 1200 and the Beijing clock time is 2000, Beijing is
   503  	// 8 hours ahead so the two dates actually represent the same instant.
   504  	timesAreEqual := timeInUTC.Equal(sameTimeInBeijing)
   505  	fmt.Println(timesAreEqual)
   506  
   507  	// Output:
   508  	// true
   509  }
   510  
   511  func ExampleTime_Add() {
   512  	start := time.Date(2009, 1, 1, 12, 0, 0, 0, time.UTC)
   513  	afterTenSeconds := start.Add(time.Second * 10)
   514  	afterTenMinutes := start.Add(time.Minute * 10)
   515  	afterTenHours := start.Add(time.Hour * 10)
   516  	afterTenDays := start.Add(time.Hour * 24 * 10)
   517  
   518  	fmt.Printf("start = %v\n", start)
   519  	fmt.Printf("start.Add(time.Second * 10) = %v\n", afterTenSeconds)
   520  	fmt.Printf("start.Add(time.Minute * 10) = %v\n", afterTenMinutes)
   521  	fmt.Printf("start.Add(time.Hour * 10) = %v\n", afterTenHours)
   522  	fmt.Printf("start.Add(time.Hour * 24 * 10) = %v\n", afterTenDays)
   523  
   524  	// Output:
   525  	// start = 2009-01-01 12:00:00 +0000 UTC
   526  	// start.Add(time.Second * 10) = 2009-01-01 12:00:10 +0000 UTC
   527  	// start.Add(time.Minute * 10) = 2009-01-01 12:10:00 +0000 UTC
   528  	// start.Add(time.Hour * 10) = 2009-01-01 22:00:00 +0000 UTC
   529  	// start.Add(time.Hour * 24 * 10) = 2009-01-11 12:00:00 +0000 UTC
   530  }
   531  
   532  func ExampleTime_AddDate() {
   533  	start := time.Date(2009, 1, 1, 0, 0, 0, 0, time.UTC)
   534  	oneDayLater := start.AddDate(0, 0, 1)
   535  	oneMonthLater := start.AddDate(0, 1, 0)
   536  	oneYearLater := start.AddDate(1, 0, 0)
   537  
   538  	fmt.Printf("oneDayLater: start.AddDate(0, 0, 1) = %v\n", oneDayLater)
   539  	fmt.Printf("oneMonthLater: start.AddDate(0, 1, 0) = %v\n", oneMonthLater)
   540  	fmt.Printf("oneYearLater: start.AddDate(1, 0, 0) = %v\n", oneYearLater)
   541  
   542  	// Output:
   543  	// oneDayLater: start.AddDate(0, 0, 1) = 2009-01-02 00:00:00 +0000 UTC
   544  	// oneMonthLater: start.AddDate(0, 1, 0) = 2009-02-01 00:00:00 +0000 UTC
   545  	// oneYearLater: start.AddDate(1, 0, 0) = 2010-01-01 00:00:00 +0000 UTC
   546  }
   547  
   548  func ExampleTime_After() {
   549  	year2000 := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
   550  	year3000 := time.Date(3000, 1, 1, 0, 0, 0, 0, time.UTC)
   551  
   552  	isYear3000AfterYear2000 := year3000.After(year2000) // True
   553  	isYear2000AfterYear3000 := year2000.After(year3000) // False
   554  
   555  	fmt.Printf("year3000.After(year2000) = %v\n", isYear3000AfterYear2000)
   556  	fmt.Printf("year2000.After(year3000) = %v\n", isYear2000AfterYear3000)
   557  
   558  	// Output:
   559  	// year3000.After(year2000) = true
   560  	// year2000.After(year3000) = false
   561  }
   562  
   563  func ExampleTime_Before() {
   564  	year2000 := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
   565  	year3000 := time.Date(3000, 1, 1, 0, 0, 0, 0, time.UTC)
   566  
   567  	isYear2000BeforeYear3000 := year2000.Before(year3000) // True
   568  	isYear3000BeforeYear2000 := year3000.Before(year2000) // False
   569  
   570  	fmt.Printf("year2000.Before(year3000) = %v\n", isYear2000BeforeYear3000)
   571  	fmt.Printf("year3000.Before(year2000) = %v\n", isYear3000BeforeYear2000)
   572  
   573  	// Output:
   574  	// year2000.Before(year3000) = true
   575  	// year3000.Before(year2000) = false
   576  }
   577  
   578  func ExampleTime_Date() {
   579  	d := time.Date(2000, 2, 1, 12, 30, 0, 0, time.UTC)
   580  	year, month, day := d.Date()
   581  
   582  	fmt.Printf("year = %v\n", year)
   583  	fmt.Printf("month = %v\n", month)
   584  	fmt.Printf("day = %v\n", day)
   585  
   586  	// Output:
   587  	// year = 2000
   588  	// month = February
   589  	// day = 1
   590  }
   591  
   592  func ExampleTime_Day() {
   593  	d := time.Date(2000, 2, 1, 12, 30, 0, 0, time.UTC)
   594  	day := d.Day()
   595  
   596  	fmt.Printf("day = %v\n", day)
   597  
   598  	// Output:
   599  	// day = 1
   600  }
   601  
   602  func ExampleTime_Equal() {
   603  	secondsEastOfUTC := int((8 * time.Hour).Seconds())
   604  	beijing := time.FixedZone("Beijing Time", secondsEastOfUTC)
   605  
   606  	// Unlike the equal operator, Equal is aware that d1 and d2 are the
   607  	// same instant but in different time zones.
   608  	d1 := time.Date(2000, 2, 1, 12, 30, 0, 0, time.UTC)
   609  	d2 := time.Date(2000, 2, 1, 20, 30, 0, 0, beijing)
   610  
   611  	datesEqualUsingEqualOperator := d1 == d2
   612  	datesEqualUsingFunction := d1.Equal(d2)
   613  
   614  	fmt.Printf("datesEqualUsingEqualOperator = %v\n", datesEqualUsingEqualOperator)
   615  	fmt.Printf("datesEqualUsingFunction = %v\n", datesEqualUsingFunction)
   616  
   617  	// Output:
   618  	// datesEqualUsingEqualOperator = false
   619  	// datesEqualUsingFunction = true
   620  }
   621  
   622  func ExampleTime_String() {
   623  	timeWithNanoseconds := time.Date(2000, 2, 1, 12, 13, 14, 15, time.UTC)
   624  	withNanoseconds := timeWithNanoseconds.String()
   625  
   626  	timeWithoutNanoseconds := time.Date(2000, 2, 1, 12, 13, 14, 0, time.UTC)
   627  	withoutNanoseconds := timeWithoutNanoseconds.String()
   628  
   629  	fmt.Printf("withNanoseconds = %v\n", string(withNanoseconds))
   630  	fmt.Printf("withoutNanoseconds = %v\n", string(withoutNanoseconds))
   631  
   632  	// Output:
   633  	// withNanoseconds = 2000-02-01 12:13:14.000000015 +0000 UTC
   634  	// withoutNanoseconds = 2000-02-01 12:13:14 +0000 UTC
   635  }
   636  
   637  func ExampleTime_Sub() {
   638  	start := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
   639  	end := time.Date(2000, 1, 1, 12, 0, 0, 0, time.UTC)
   640  
   641  	difference := end.Sub(start)
   642  	fmt.Printf("difference = %v\n", difference)
   643  
   644  	// Output:
   645  	// difference = 12h0m0s
   646  }
   647  
   648  func ExampleTime_AppendFormat() {
   649  	t := time.Date(2017, time.November, 4, 11, 0, 0, 0, time.UTC)
   650  	text := []byte("Time: ")
   651  
   652  	text = t.AppendFormat(text, time.Kitchen)
   653  	fmt.Println(string(text))
   654  
   655  	// Output:
   656  	// Time: 11:00AM
   657  }
   658  
   659  func ExampleFixedZone() {
   660  	loc := time.FixedZone("UTC-8", -8*60*60)
   661  	t := time.Date(2009, time.November, 10, 23, 0, 0, 0, loc)
   662  	fmt.Println("The time is:", t.Format(time.RFC822))
   663  	// Output: The time is: 10 Nov 09 23:00 UTC-8
   664  }
   665  

View as plain text