Source file src/time/example_test.go

     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  	"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  	// Output:
    43  	// d.Round(   1ns) = 1h15m30.918273645s
    44  	// d.Round(   1µs) = 1h15m30.918274s
    45  	// d.Round(   1ms) = 1h15m30.918s
    46  	// d.Round(    1s) = 1h15m31s
    47  	// d.Round(    2s) = 1h15m30s
    48  	// d.Round(  1m0s) = 1h16m0s
    49  	// d.Round( 10m0s) = 1h20m0s
    50  	// d.Round(1h0m0s) = 1h0m0s
    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  	// Output:
    57  	// 1h2m0.3s
    58  	// 300ms
    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  	// Output:
    82  	// d.Truncate(   1ns) = 1h15m30.918273645s
    83  	// d.Truncate(   1µs) = 1h15m30.918273s
    84  	// d.Truncate(   1ms) = 1h15m30.918s
    85  	// d.Truncate(    1s) = 1h15m30s
    86  	// d.Truncate(    2s) = 1h15m30s
    87  	// d.Truncate(  1m0s) = 1h15m0s
    88  	// d.Truncate( 10m0s) = 1h10m0s
    89  	// d.Truncate(1h0m0s) = 1h0m0s
    90  }
    91  
    92  func ExampleParseDuration() {
    93  	hours, _ := time.ParseDuration("10h")
    94  	complex, _ := time.ParseDuration("1h10m10s")
    95  	micro, _ := time.ParseDuration("1µs")
    96  	// The package also accepts the incorrect but common prefix u for micro.
    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  	// Output:
   105  	// 10h0m0s
   106  	// 1h10m10s
   107  	// There are 4210 seconds in 1h10m10s.
   108  	// There are 1000 nanoseconds in 1µs.
   109  	// There are 1.00e-06 seconds in 1µs.
   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  	// Output: Duration until future time: 5 seconds
   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  	// Output:
   140  	// Absolute value of positive duration: 5s
   141  	// Absolute value of negative duration: 3s
   142  	// Absolute value of MinInt64 equal to MaxInt64: true
   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  	// Output: I've got 4.5 hours of work left.
   149  }
   150  
   151  func ExampleDuration_Microseconds() {
   152  	u, _ := time.ParseDuration("1s")
   153  	fmt.Printf("One second is %d microseconds.\n", u.Microseconds())
   154  	// Output:
   155  	// One second is 1000000 microseconds.
   156  }
   157  
   158  func ExampleDuration_Milliseconds() {
   159  	u, _ := time.ParseDuration("1s")
   160  	fmt.Printf("One second is %d milliseconds.\n", u.Milliseconds())
   161  	// Output:
   162  	// One second is 1000 milliseconds.
   163  }
   164  
   165  func ExampleDuration_Minutes() {
   166  	m, _ := time.ParseDuration("1h30m")
   167  	fmt.Printf("The movie is %.0f minutes long.", m.Minutes())
   168  	// Output: The movie is 90 minutes long.
   169  }
   170  
   171  func ExampleDuration_Nanoseconds() {
   172  	u, _ := time.ParseDuration("1µs")
   173  	fmt.Printf("One microsecond is %d nanoseconds.\n", u.Nanoseconds())
   174  	// Output:
   175  	// One microsecond is 1000 nanoseconds.
   176  }
   177  
   178  func ExampleDuration_Seconds() {
   179  	m, _ := time.ParseDuration("1m30s")
   180  	fmt.Printf("Take off in t-%.0f seconds.", m.Seconds())
   181  	// Output: Take off in t-90 seconds.
   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  	// Output: Go launched at 2009-11-10 15:00:00 -0800 PST
   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  	// Parse a time value from a string in the standard Unix format.
   244  	t, err := time.Parse(time.UnixDate, "Wed Feb 25 11:06:39 PST 2015")
   245  	if err != nil { // Always check errors even if they should not happen.
   246  		panic(err)
   247  	}
   248  
   249  	tz, err := time.LoadLocation("Asia/Shanghai")
   250  	if err != nil { // Always check errors even if they should not happen.
   251  		panic(err)
   252  	}
   253  
   254  	// time.Time's Stringer method is useful without any format.
   255  	fmt.Println("default format:", t)
   256  
   257  	// Predefined constants in the package implement common layouts.
   258  	fmt.Println("Unix format:", t.Format(time.UnixDate))
   259  
   260  	// The time zone attached to the time value affects its output.
   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  	// The rest of this function demonstrates the properties of the
   268  	// layout string used in the format.
   269  
   270  	// The layout string used by the Parse function and Format method
   271  	// shows by example how the reference time should be represented.
   272  	// We stress that one must show how the reference time is formatted,
   273  	// not a time of the user's choosing. Thus each layout string is a
   274  	// representation of the time stamp,
   275  	//	Jan 2 15:04:05 2006 MST
   276  	// An easy way to remember this value is that it holds, when presented
   277  	// in this order, the values (lined up with the elements above):
   278  	//	  1 2  3  4  5    6  -7
   279  	// There are some wrinkles illustrated below.
   280  
   281  	// Most uses of Format and Parse use constant layout strings such as
   282  	// the ones defined in this package, but the interface is flexible,
   283  	// as these examples show.
   284  
   285  	// Define a helper function to make the examples' output look nice.
   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  	// Print a header in our output.
   296  	fmt.Printf("\nFormats:\n\n")
   297  
   298  	// Simple starter examples.
   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  	// The hour of the reference time is 15, or 3PM. The layout can express
   303  	// it either way, and since our value is the morning we should see it as
   304  	// an AM time. We show both in one format string. Lower case too.
   305  	do("AM/PM", "3PM==3pm==15h", "11AM==11am==11h")
   306  
   307  	// When parsing, if the seconds value is followed by a decimal point
   308  	// and some digits, that is taken as a fraction of a second even if
   309  	// the layout string does not represent the fractional second.
   310  	// Here we add a fractional second to our time value used above.
   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  	// It does not appear in the output if the layout string does not contain
   316  	// a representation of the fractional second.
   317  	do("No fraction", time.UnixDate, "Wed Feb 25 11:06:39 PST 2015")
   318  
   319  	// Fractional seconds can be printed by adding a run of 0s or 9s after
   320  	// a decimal point in the seconds value in the layout string.
   321  	// If the layout digits are 0s, the fractional second is of the specified
   322  	// width. Note that the output has a trailing zero.
   323  	do("0s for fraction", "15:04:05.00000", "11:06:39.12340")
   324  
   325  	// If the fraction in the layout is 9s, trailing zeros are dropped.
   326  	do("9s for fraction", "15:04:05.99999999", "11:06:39.1234")
   327  
   328  	// Output:
   329  	// default format: 2015-02-25 11:06:39 -0800 PST
   330  	// Unix format: Wed Feb 25 11:06:39 PST 2015
   331  	// Same, in UTC: Wed Feb 25 19:06:39 UTC 2015
   332  	// in Shanghai with seconds: 2015-02-26T03:06:39 +080000
   333  	// in Shanghai with colon seconds: 2015-02-26T03:06:39 +08:00:00
   334  	//
   335  	// Formats:
   336  	//
   337  	// Basic full date  "Mon Jan 2 15:04:05 MST 2006" gives "Wed Feb 25 11:06:39 PST 2015"
   338  	// Basic short date "2006/01/02" gives "2015/02/25"
   339  	// AM/PM            "3PM==3pm==15h" gives "11AM==11am==11h"
   340  	// No fraction      "Mon Jan _2 15:04:05 MST 2006" gives "Wed Feb 25 11:06:39 PST 2015"
   341  	// 0s for fraction  "15:04:05.00000" gives "11:06:39.12340"
   342  	// 9s for fraction  "15:04:05.99999999" gives "11:06:39.1234"
   343  
   344  }
   345  
   346  func ExampleTime_Format_pad() {
   347  	// Parse a time value from a string in the standard Unix format.
   348  	t, err := time.Parse(time.UnixDate, "Sat Mar 7 11:06:39 PST 2015")
   349  	if err != nil { // Always check errors even if they should not happen.
   350  		panic(err)
   351  	}
   352  
   353  	// Define a helper function to make the examples' output look nice.
   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  	// The predefined constant Unix uses an underscore to pad the day.
   364  	do("Unix", time.UnixDate, "Sat Mar  7 11:06:39 PST 2015")
   365  
   366  	// For fixed-width printing of values, such as the date, that may be one or
   367  	// two characters (7 vs. 07), use an _ instead of a space in the layout string.
   368  	// Here we print just the day, which is 2 in our layout string and 7 in our
   369  	// value.
   370  	do("No pad", "<2>", "<7>")
   371  
   372  	// An underscore represents a space pad, if the date only has one digit.
   373  	do("Spaces", "<_2>", "< 7>")
   374  
   375  	// A "0" indicates zero padding for single-digit values.
   376  	do("Zeros", "<02>", "<07>")
   377  
   378  	// If the value is already the right width, padding is not used.
   379  	// For instance, the second (05 in the reference time) in our value is 39,
   380  	// so it doesn't need padding, but the minutes (04, 06) does.
   381  	do("Suppressed pad", "04:05", "06:39")
   382  
   383  	// Output:
   384  	// Unix             "Mon Jan _2 15:04:05 MST 2006" gives "Sat Mar  7 11:06:39 PST 2015"
   385  	// No pad           "<2>" gives "<7>"
   386  	// Spaces           "<_2>" gives "< 7>"
   387  	// Zeros            "<02>" gives "<07>"
   388  	// Suppressed pad   "04:05" gives "06:39"
   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  	// Output:
   403  	// time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
   404  	// time.Date(2009, time.November, 10, 23, 1, 0, 0, time.UTC)
   405  	// time.Date(2009, time.December, 10, 23, 1, 0, 0, time.UTC)
   406  	// time.Date(2013, time.February, 3, 19, 54, 0, 0, time.UTC)
   407  }
   408  
   409  func ExampleParse() {
   410  	// See the example for Time.Format for a thorough description of how
   411  	// to define the layout string to parse a time.Time value; Parse and
   412  	// Format use the same model to describe their input and output.
   413  
   414  	// longForm shows by example how the reference time would be represented in
   415  	// the desired layout.
   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  	// shortForm is another way the reference time would be represented
   421  	// in the desired layout; it has no time zone present.
   422  	// Note: without explicit zone, returns time in UTC.
   423  	const shortForm = "2006-Jan-02"
   424  	t, _ = time.Parse(shortForm, "2013-Feb-03")
   425  	fmt.Println(t)
   426  
   427  	// Some valid layouts are invalid time values, due to format specifiers
   428  	// such as _ for space padding and Z for zone information.
   429  	// For example the RFC3339 layout 2006-01-02T15:04:05Z07:00
   430  	// contains both Z and a time zone offset in order to handle both valid options:
   431  	// 2006-01-02T15:04:05Z
   432  	// 2006-01-02T15:04:05+07:00
   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) // Returns an error as the layout is not a valid time value
   439  
   440  	// Output:
   441  	// 2013-02-03 19:54:00 -0800 PST
   442  	// 2013-02-03 00:00:00 +0000 UTC
   443  	// 2006-01-02 15:04:05 +0000 UTC
   444  	// 2006-01-02 15:04:05 +0700 +0700
   445  	// error parsing time "2006-01-02T15:04:05Z07:00": extra text: "07:00"
   446  }
   447  
   448  func ExampleParseInLocation() {
   449  	loc, _ := time.LoadLocation("Europe/Berlin")
   450  
   451  	// This will look for the name CEST in the Europe/Berlin time zone.
   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  	// Note: without explicit zone, returns time in given location.
   457  	const shortForm = "2006-Jan-02"
   458  	t, _ = time.ParseInLocation(shortForm, "2012-Jul-09", loc)
   459  	fmt.Println(t)
   460  
   461  	// Output:
   462  	// 2012-07-09 05:02:00 +0200 CEST
   463  	// 2012-07-09 00:00:00 +0200 CEST
   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  	// Output:
   473  	// 1257894000
   474  	// 2009-11-10 23:00:00 +0000 UTC
   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  	// Output:
   484  	// 1257894000000000
   485  	// 2009-11-10 23:00:00 +0000 UTC
   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  	// Output:
   495  	// 1257894000000
   496  	// 2009-11-10 23:00:00 +0000 UTC
   497  }
   498  
   499  func ExampleTime_Unix() {
   500  	// 1 billion seconds of Unix, three ways.
   501  	fmt.Println(time.Unix(1e9, 0).UTC())     // 1e9 seconds
   502  	fmt.Println(time.Unix(0, 1e18).UTC())    // 1e18 nanoseconds
   503  	fmt.Println(time.Unix(2e9, -1e18).UTC()) // 2e9 seconds - 1e18 nanoseconds
   504  
   505  	t := time.Date(2001, time.September, 9, 1, 46, 40, 0, time.UTC)
   506  	fmt.Println(t.Unix())     // seconds since 1970
   507  	fmt.Println(t.UnixNano()) // nanoseconds since 1970
   508  
   509  	// Output:
   510  	// 2001-09-09 01:46:40 +0000 UTC
   511  	// 2001-09-09 01:46:40 +0000 UTC
   512  	// 2001-09-09 01:46:40 +0000 UTC
   513  	// 1000000000
   514  	// 1000000000000000000
   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  	// Output:
   534  	// t.Round(   1ns) = 12:15:30.918273645
   535  	// t.Round(   1µs) = 12:15:30.918274
   536  	// t.Round(   1ms) = 12:15:30.918
   537  	// t.Round(    1s) = 12:15:31
   538  	// t.Round(    2s) = 12:15:30
   539  	// t.Round(  1m0s) = 12:16:00
   540  	// t.Round( 10m0s) = 12:20:00
   541  	// t.Round(1h0m0s) = 12:00:00
   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  	// To round to the last midnight in the local timezone, create a new Date.
   560  	midnight := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.Local)
   561  	_ = midnight
   562  
   563  	// Output:
   564  	// t.Truncate(  1ns) = 12:15:30.918273645
   565  	// t.Truncate(  1µs) = 12:15:30.918273
   566  	// t.Truncate(  1ms) = 12:15:30.918
   567  	// t.Truncate(   1s) = 12:15:30
   568  	// t.Truncate(   2s) = 12:15:30
   569  	// t.Truncate( 1m0s) = 12:15:00
   570  	// t.Truncate(10m0s) = 12:10:00
   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  	// Output: 2018-08-30 05:00:00 -0700 PDT
   582  }
   583  
   584  func ExampleLocation() {
   585  	// China doesn't have daylight saving. It uses a fixed 8 hour offset from UTC.
   586  	secondsEastOfUTC := int((8 * time.Hour).Seconds())
   587  	beijing := time.FixedZone("Beijing Time", secondsEastOfUTC)
   588  
   589  	// If the system has a timezone database present, it's possible to load a location
   590  	// from that, e.g.:
   591  	//    newYork, err := time.LoadLocation("America/New_York")
   592  
   593  	// Creating a time requires a location. Common locations are time.Local and time.UTC.
   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  	// Although the UTC clock time is 1200 and the Beijing clock time is 2000, Beijing is
   598  	// 8 hours ahead so the two dates actually represent the same instant.
   599  	timesAreEqual := timeInUTC.Equal(sameTimeInBeijing)
   600  	fmt.Println(timesAreEqual)
   601  
   602  	// Output:
   603  	// true
   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  	// Output:
   620  	// start = 2009-01-01 12:00:00 +0000 UTC
   621  	// start.Add(time.Second * 10) = 2009-01-01 12:00:10 +0000 UTC
   622  	// start.Add(time.Minute * 10) = 2009-01-01 12:10:00 +0000 UTC
   623  	// start.Add(time.Hour * 10) = 2009-01-01 22:00:00 +0000 UTC
   624  	// start.Add(time.Hour * 24 * 10) = 2009-01-11 12:00:00 +0000 UTC
   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  	// This was the day before a daylight saving time transition in Zürich.
   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  	// Output:
   650  	// oneDayLater: start.AddDate(0, 0, 1) = 2023-03-26 12:00:00 +0000 UTC
   651  	// oneMonthLater: start.AddDate(0, 1, 0) = 2023-04-25 12:00:00 +0000 UTC
   652  	// oneYearLater: start.AddDate(1, 0, 0) = 2024-03-25 12:00:00 +0000 UTC
   653  	// oneDayLaterZurich: startZurich.AddDate(0, 0, 1) = 2023-03-26 12:00:00 +0200 CEST
   654  	// Day duration in UTC: 24h0m0s | Day duration in Zürich: 23h0m0s
   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) // True
   662  	isYear2000AfterYear3000 := year2000.After(year3000) // False
   663  
   664  	fmt.Printf("year3000.After(year2000) = %v\n", isYear3000AfterYear2000)
   665  	fmt.Printf("year2000.After(year3000) = %v\n", isYear2000AfterYear3000)
   666  
   667  	// Output:
   668  	// year3000.After(year2000) = true
   669  	// year2000.After(year3000) = false
   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) // True
   677  	isYear3000BeforeYear2000 := year3000.Before(year2000) // False
   678  
   679  	fmt.Printf("year2000.Before(year3000) = %v\n", isYear2000BeforeYear3000)
   680  	fmt.Printf("year3000.Before(year2000) = %v\n", isYear3000BeforeYear2000)
   681  
   682  	// Output:
   683  	// year2000.Before(year3000) = true
   684  	// year3000.Before(year2000) = false
   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  	// Output:
   696  	// year = 2000
   697  	// month = February
   698  	// day = 1
   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  	// Output:
   708  	// day = 1
   709  }
   710  
   711  func ExampleTime_Equal() {
   712  	secondsEastOfUTC := int((8 * time.Hour).Seconds())
   713  	beijing := time.FixedZone("Beijing Time", secondsEastOfUTC)
   714  
   715  	// Unlike the equal operator, Equal is aware that d1 and d2 are the
   716  	// same instant but in different time zones.
   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  	// Output:
   727  	// datesEqualUsingEqualOperator = false
   728  	// datesEqualUsingFunction = true
   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  	// Output:
   742  	// withNanoseconds = 2000-02-01 12:13:14.000000015 +0000 UTC
   743  	// withoutNanoseconds = 2000-02-01 12:13:14 +0000 UTC
   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  	// Output:
   754  	// difference = 12h0m0s
   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  	// Output:
   765  	// Time: 11:00AM
   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  	// Output: The time is: 10 Nov 09 23:00 UTC-8
   773  }
   774  

View as plain text