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

View as plain text