Home | History | Annotate | Download | only in 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 var c chan int
     22 
     23 func handle(int) {}
     24 
     25 func ExampleAfter() {
     26 	select {
     27 	case m := <-c:
     28 		handle(m)
     29 	case <-time.After(5 * time.Minute):
     30 		fmt.Println("timed out")
     31 	}
     32 }
     33 
     34 func ExampleSleep() {
     35 	time.Sleep(100 * time.Millisecond)
     36 }
     37 
     38 func statusUpdate() string { return "" }
     39 
     40 func ExampleTick() {
     41 	c := time.Tick(1 * time.Minute)
     42 	for now := range c {
     43 		fmt.Printf("%v %s\n", now, statusUpdate())
     44 	}
     45 }
     46 
     47 func ExampleMonth() {
     48 	_, month, day := time.Now().Date()
     49 	if month == time.November && day == 10 {
     50 		fmt.Println("Happy Go day!")
     51 	}
     52 }
     53 
     54 func ExampleDate() {
     55 	t := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
     56 	fmt.Printf("Go launched at %s\n", t.Local())
     57 	// Output: Go launched at 2009-11-10 15:00:00 -0800 PST
     58 }
     59 
     60 func ExampleTime_Format() {
     61 	// Parse a time value from a string in the standard Unix format.
     62 	t, err := time.Parse(time.UnixDate, "Sat Mar  7 11:06:39 PST 2015")
     63 	if err != nil { // Always check errors even if they should not happen.
     64 		panic(err)
     65 	}
     66 
     67 	// time.Time's Stringer method is useful without any format.
     68 	fmt.Println("default format:", t)
     69 
     70 	// Predefined constants in the package implement common layouts.
     71 	fmt.Println("Unix format:", t.Format(time.UnixDate))
     72 
     73 	// The time zone attached to the time value affects its output.
     74 	fmt.Println("Same, in UTC:", t.UTC().Format(time.UnixDate))
     75 
     76 	// The rest of this function demonstrates the properties of the
     77 	// layout string used in the format.
     78 
     79 	// The layout string used by the Parse function and Format method
     80 	// shows by example how the reference time should be represented.
     81 	// We stress that one must show how the reference time is formatted,
     82 	// not a time of the user's choosing. Thus each layout string is a
     83 	// representation of the time stamp,
     84 	//	Jan 2 15:04:05 2006 MST
     85 	// An easy way to remember this value is that it holds, when presented
     86 	// in this order, the values (lined up with the elements above):
     87 	//	  1 2  3  4  5    6  -7
     88 	// There are some wrinkles illustrated below.
     89 
     90 	// Most uses of Format and Parse use constant layout strings such as
     91 	// the ones defined in this package, but the interface is flexible,
     92 	// as these examples show.
     93 
     94 	// Define a helper function to make the examples' output look nice.
     95 	do := func(name, layout, want string) {
     96 		got := t.Format(layout)
     97 		if want != got {
     98 			fmt.Printf("error: for %q got %q; expected %q\n", layout, got, want)
     99 			return
    100 		}
    101 		fmt.Printf("%-15s %q gives %q\n", name, layout, got)
    102 	}
    103 
    104 	// Print a header in our output.
    105 	fmt.Printf("\nFormats:\n\n")
    106 
    107 	// A simple starter example.
    108 	do("Basic", "Mon Jan 2 15:04:05 MST 2006", "Sat Mar 7 11:06:39 PST 2015")
    109 
    110 	// For fixed-width printing of values, such as the date, that may be one or
    111 	// two characters (7 vs. 07), use an _ instead of a space in the layout string.
    112 	// Here we print just the day, which is 2 in our layout string and 7 in our
    113 	// value.
    114 	do("No pad", "<2>", "<7>")
    115 
    116 	// An underscore represents a zero pad, if required.
    117 	do("Spaces", "<_2>", "< 7>")
    118 
    119 	// Similarly, a 0 indicates zero padding.
    120 	do("Zeros", "<02>", "<07>")
    121 
    122 	// If the value is already the right width, padding is not used.
    123 	// For instance, the second (05 in the reference time) in our value is 39,
    124 	// so it doesn't need padding, but the minutes (04, 06) does.
    125 	do("Suppressed pad", "04:05", "06:39")
    126 
    127 	// The predefined constant Unix uses an underscore to pad the day.
    128 	// Compare with our simple starter example.
    129 	do("Unix", time.UnixDate, "Sat Mar  7 11:06:39 PST 2015")
    130 
    131 	// The hour of the reference time is 15, or 3PM. The layout can express
    132 	// it either way, and since our value is the morning we should see it as
    133 	// an AM time. We show both in one format string. Lower case too.
    134 	do("AM/PM", "3PM==3pm==15h", "11AM==11am==11h")
    135 
    136 	// When parsing, if the seconds value is followed by a decimal point
    137 	// and some digits, that is taken as a fraction of a second even if
    138 	// the layout string does not represent the fractional second.
    139 	// Here we add a fractional second to our time value used above.
    140 	t, err = time.Parse(time.UnixDate, "Sat Mar  7 11:06:39.1234 PST 2015")
    141 	if err != nil {
    142 		panic(err)
    143 	}
    144 	// It does not appear in the output if the layout string does not contain
    145 	// a representation of the fractional second.
    146 	do("No fraction", time.UnixDate, "Sat Mar  7 11:06:39 PST 2015")
    147 
    148 	// Fractional seconds can be printed by adding a run of 0s or 9s after
    149 	// a decimal point in the seconds value in the layout string.
    150 	// If the layout digits are 0s, the fractional second is of the specified
    151 	// width. Note that the output has a trailing zero.
    152 	do("0s for fraction", "15:04:05.00000", "11:06:39.12340")
    153 
    154 	// If the fraction in the layout is 9s, trailing zeros are dropped.
    155 	do("9s for fraction", "15:04:05.99999999", "11:06:39.1234")
    156 
    157 	// Output:
    158 	// default format: 2015-03-07 11:06:39 -0800 PST
    159 	// Unix format: Sat Mar  7 11:06:39 PST 2015
    160 	// Same, in UTC: Sat Mar  7 19:06:39 UTC 2015
    161 	//
    162 	// Formats:
    163 	//
    164 	// Basic           "Mon Jan 2 15:04:05 MST 2006" gives "Sat Mar 7 11:06:39 PST 2015"
    165 	// No pad          "<2>" gives "<7>"
    166 	// Spaces          "<_2>" gives "< 7>"
    167 	// Zeros           "<02>" gives "<07>"
    168 	// Suppressed pad  "04:05" gives "06:39"
    169 	// Unix            "Mon Jan _2 15:04:05 MST 2006" gives "Sat Mar  7 11:06:39 PST 2015"
    170 	// AM/PM           "3PM==3pm==15h" gives "11AM==11am==11h"
    171 	// No fraction     "Mon Jan _2 15:04:05 MST 2006" gives "Sat Mar  7 11:06:39 PST 2015"
    172 	// 0s for fraction "15:04:05.00000" gives "11:06:39.12340"
    173 	// 9s for fraction "15:04:05.99999999" gives "11:06:39.1234"
    174 
    175 }
    176 
    177 func ExampleParse() {
    178 	// See the example for time.Format for a thorough description of how
    179 	// to define the layout string to parse a time.Time value; Parse and
    180 	// Format use the same model to describe their input and output.
    181 
    182 	// longForm shows by example how the reference time would be represented in
    183 	// the desired layout.
    184 	const longForm = "Jan 2, 2006 at 3:04pm (MST)"
    185 	t, _ := time.Parse(longForm, "Feb 3, 2013 at 7:54pm (PST)")
    186 	fmt.Println(t)
    187 
    188 	// shortForm is another way the reference time would be represented
    189 	// in the desired layout; it has no time zone present.
    190 	// Note: without explicit zone, returns time in UTC.
    191 	const shortForm = "2006-Jan-02"
    192 	t, _ = time.Parse(shortForm, "2013-Feb-03")
    193 	fmt.Println(t)
    194 
    195 	// Output:
    196 	// 2013-02-03 19:54:00 -0800 PST
    197 	// 2013-02-03 00:00:00 +0000 UTC
    198 }
    199 
    200 func ExampleParseInLocation() {
    201 	loc, _ := time.LoadLocation("Europe/Berlin")
    202 
    203 	const longForm = "Jan 2, 2006 at 3:04pm (MST)"
    204 	t, _ := time.ParseInLocation(longForm, "Jul 9, 2012 at 5:02am (CEST)", loc)
    205 	fmt.Println(t)
    206 
    207 	// Note: without explicit zone, returns time in given location.
    208 	const shortForm = "2006-Jan-02"
    209 	t, _ = time.ParseInLocation(shortForm, "2012-Jul-09", loc)
    210 	fmt.Println(t)
    211 
    212 	// Output:
    213 	// 2012-07-09 05:02:00 +0200 CEST
    214 	// 2012-07-09 00:00:00 +0200 CEST
    215 }
    216 
    217 func ExampleTime_Round() {
    218 	t := time.Date(0, 0, 0, 12, 15, 30, 918273645, time.UTC)
    219 	round := []time.Duration{
    220 		time.Nanosecond,
    221 		time.Microsecond,
    222 		time.Millisecond,
    223 		time.Second,
    224 		2 * time.Second,
    225 		time.Minute,
    226 		10 * time.Minute,
    227 		time.Hour,
    228 	}
    229 
    230 	for _, d := range round {
    231 		fmt.Printf("t.Round(%6s) = %s\n", d, t.Round(d).Format("15:04:05.999999999"))
    232 	}
    233 	// Output:
    234 	// t.Round(   1ns) = 12:15:30.918273645
    235 	// t.Round(   1s) = 12:15:30.918274
    236 	// t.Round(   1ms) = 12:15:30.918
    237 	// t.Round(    1s) = 12:15:31
    238 	// t.Round(    2s) = 12:15:30
    239 	// t.Round(  1m0s) = 12:16:00
    240 	// t.Round( 10m0s) = 12:20:00
    241 	// t.Round(1h0m0s) = 12:00:00
    242 }
    243 
    244 func ExampleTime_Truncate() {
    245 	t, _ := time.Parse("2006 Jan 02 15:04:05", "2012 Dec 07 12:15:30.918273645")
    246 	trunc := []time.Duration{
    247 		time.Nanosecond,
    248 		time.Microsecond,
    249 		time.Millisecond,
    250 		time.Second,
    251 		2 * time.Second,
    252 		time.Minute,
    253 		10 * time.Minute,
    254 		time.Hour,
    255 	}
    256 
    257 	for _, d := range trunc {
    258 		fmt.Printf("t.Truncate(%6s) = %s\n", d, t.Truncate(d).Format("15:04:05.999999999"))
    259 	}
    260 
    261 	// Output:
    262 	// t.Truncate(   1ns) = 12:15:30.918273645
    263 	// t.Truncate(   1s) = 12:15:30.918273
    264 	// t.Truncate(   1ms) = 12:15:30.918
    265 	// t.Truncate(    1s) = 12:15:30
    266 	// t.Truncate(    2s) = 12:15:30
    267 	// t.Truncate(  1m0s) = 12:15:00
    268 	// t.Truncate( 10m0s) = 12:10:00
    269 	// t.Truncate(1h0m0s) = 12:00:00
    270 }
    271