本實驗旨在測試您對 Go 的時間和持續時間支援的理解。
下面的程式碼包含如何在 Go 中使用時間和持續時間的範例。但是,程式碼的某些部分遺失了。您的任務是完成程式碼,使其按預期工作。
$ go run time.go 2012-10-31 15:50:13.793654 0000 UTC 2009-11-17 20:34:58.651387237 0000 UTC 2009 November 17 20 34 58 651387237 UTC Tuesday true false false 25891h15m15.142266763s 25891.25420618521 1.5534752523711128e 06 9.320851514226677e 07 93208515142266763 2012-10-31 15:50:13.793654 0000 UTC 2006-12-05 01:19:43.509120474 0000 UTC # Next we'll look at the related idea of time relative to # the Unix epoch.
完整程式碼如下:
// Go offers extensive support for times and durations; // here are some examples. package main import ( "fmt" "time" ) func main() { p := fmt.Println // We'll start by getting the current time. now := time.Now() p(now) // You can build a `time` struct by providing the // year, month, day, etc. Times are always associated // with a `Location`, i.e. time zone. then := time.Date( 2009, 11, 17, 20, 34, 58, 651387237, time.UTC) p(then) // You can extract the various components of the time // value as expected. p(then.Year()) p(then.Month()) p(then.Day()) p(then.Hour()) p(then.Minute()) p(then.Second()) p(then.Nanosecond()) p(then.Location()) // The Monday-Sunday `Weekday` is also available. p(then.Weekday()) // These methods compare two times, testing if the // first occurs before, after, or at the same time // as the second, respectively. p(then.Before(now)) p(then.After(now)) p(then.Equal(now)) // The `Sub` methods returns a `Duration` representing // the interval between two times. diff := now.Sub(then) p(diff) // We can compute the length of the duration in // various units. p(diff.Hours()) p(diff.Minutes()) p(diff.Seconds()) p(diff.Nanoseconds()) // You can use `Add` to advance a time by a given // duration, or with a `-` to move backwards by a // duration. p(then.Add(diff)) p(then.Add(-diff)) }
本實驗室測試了您使用 Go 的時間和持續時間支援的能力。您學習如何提取時間值的各個組成部分、比較兩次、計算持續時間的長度以及將時間提前給定的持續時間。
?立即練習:探索時間和持續時間
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3