pub struct Time { /* private fields */ }Expand description
A Time represents an instant in time with nanosecond precision. Programs using times should typically store and pass them as values, not pointers. That is, time variables and struct fields should be of type time.Time, not *time.Time.
A Time value can be used by multiple goroutines simultaneously except that the methods GobDecode, UnmarshalBinary, UnmarshalJSON and UnmarshalText are not concurrency-safe.
Time instants can be compared using the Before, After, and Equal methods. The Sub method subtracts two instants, producing a Duration. The Add method adds a Time and a Duration, producing a Time.
The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC. As this time is unlikely to come up in practice, the IsZero method gives a simple way of detecting a time that has not been initialized explicitly.
Each Time has associated with it a Location, consulted when computing the presentation form of the time, such as in the Format, Hour, and Year methods. The methods Local, UTC, and In return a Time with a specific location. Changing the location in this way changes only the presentation; it does not change the instant in time being denoted and therefore does not affect the computations described in earlier paragraphs.
Representations of a Time value saved by the GobEncode, MarshalBinary, MarshalJSON, and MarshalText methods store the Time.Location’s offset, but not the location name. They therefore lose information about Daylight Saving Time.
In addition to the required “wall clock” reading, a Time may contain an optional reading of the current process’s monotonic clock, to provide additional precision for comparison or subtraction. See the “Monotonic Clocks” section in the package documentation for details.
Note that the Go == operator compares not just the time instant but also the Location and the monotonic clock reading. Therefore, Time values should not be used as map or database keys without first guaranteeing that the identical Location has been set for all values, which can be achieved through use of the UTC or Local method, and that the monotonic clock reading has been stripped by setting t = t.Round(0). In general, prefer t.Equal(u) to t == u, since t.Equal uses the most accurate comparison available and correctly handles the case when only one of its arguments has a monotonic clock reading.
zh-cn
Time代表一个纳秒精度的时间点。 程序中应使用Time类型值来保存和传递时间,而不能用指针。就是说,表示时间的变量和字段,应为time.Time类型,而不是*time.Time.类型。一个Time类型值可以被多个go程同时使用。时间点可以使用Before、After和Equal方法进行比较。Sub方法让两个时间点相减,生成一个Duration类型值(代表时间段)。Add方法给一个时间点加上一个时间段,生成一个新的Time类型时间点。 Time零值代表时间点January 1, year 1, 00:00:00.000000000 UTC。因为本时间点一般不会出现在使用中,IsZero方法提供了检验时间是否显式初始化的一个简单途径。 每一个时间都具有一个地点信息(及对应地点的时区信息),当计算时间的表示格式时,如Format、Hour和Year等方法,都会考虑该信息。Local、UTC和In方法返回一个指定时区(但指向同一时间点)的Time。修改地点/时区信息只是会改变其表示;不会修改被表示的时间点,因此也不会影响其计算。Implementations§
Source§impl Time
impl Time
Sourcepub fn Format(&self, layout: &str) -> string
pub fn Format(&self, layout: &str) -> string
Format returns a textual representation of the time value formatted according to the layout defined by the argument. See the documentation for the constant called Layout to see how to represent the layout format.
The executable example for Time.Format demonstrates the working of the layout string in detail and is a good reference.
zh-cn
Format根据layout指定的格式返回t代表的时间点的格式化文本表示。layout定义了参考时间:Mon Jan 2 15:04:05 -0700 MST 2006
格式化后的字符串表示,它作为期望输出的例子。同样的格式规则会被用于格式化时间。
预定义的ANSIC、UnixDate、RFC3339和其他版式描述了参考时间的标准或便捷表示。要获得更多参考时间的定义和格式,参见本包的ANSIC和其他版式常量。
§Example
use gostd_time as time;
let t = time::Date(3509, 11, 10, 14, 30, 12, 13, time::UTC.clone());
assert_eq!(t.String(),"3509-11-10 14:30:12.000000013 +0000 UTC".to_string());
assert_eq!(t.Format(time::RFC822),"10 Nov 09 14:30 UTC".to_string());
assert_eq!(t.Format(time::RFC1123),"Wed, 10 Nov 3509 14:30:12 UTC".to_string());
assert_eq!("Wednesday",t.Weekday().String());
println!("default: {}", t);
println!("RFC822: {}", t.Format(time::RFC822));
println!("RFC1123: {}", t.Format(time::RFC1123));§Output:
default: 2009-11-10 14:30:12.000000013 +0000 UTC
RFC822: 11/10 02:30:12PM '09 +0000
RFC1123: Tue, 10 Nov 2009 14:30:12 UTCSourcepub fn String(&self) -> string
pub fn String(&self) -> string
String returns the time formatted using the format string
2006-01-02 15:04:05.999999999 -0700 MST
If the time has a monotonic clock reading, the returned string includes a final field m=±<value>, where value is the monotonic clock reading formatted as a decimal number of seconds.
zh-cn
String 返回使用格式化字符串的时间2006-01-02 15:04:05.999999999 -0700 MST
如果时间有一个单调的时钟读数,返回的字符串包括最后一个字段 m=±<value>,其中value是单调的时钟读数,格式为十进制的秒数。
Sourcepub fn After(&self, u: &Time) -> bool
pub fn After(&self, u: &Time) -> bool
Sourcepub fn Before(&self, u: &Time) -> bool
pub fn Before(&self, u: &Time) -> bool
Before reports whether the time instant self is before u.
zh-cn
如果self代表的时间点在u之前,返回真;否则返回假。§Example
Sourcepub fn Equal(&self, u: &Time) -> bool
pub fn Equal(&self, u: &Time) -> bool
Equal reports whether t and u represent the same time instant. Two times can be equal even if they are in different locations. For example, 6:00 +0200 and 4:00 UTC are Equal. See the documentation on the Time type for the pitfalls of using == with Time values; most code should use Equal instead.
zh-cn
判断两个时间是否相同,会考虑时区的影响,因此不同时区标准的时间也可以正确比较。本方法和用t==u不同,这种方法还会比较地点和时区信息。§Example
use gostd_builtin::*;
use gostd_time as time;
let secondsEastOfUTC = int!(time::Duration::new(8 * time::Hour).Seconds());
let beijing = time::FixedZone("Beijing Time", secondsEastOfUTC);///
// Unlike the equal operator, Equal is aware that d1 and d2 are the
// same instant but in different time zones.
let d1 = time::Date(2000, 2, 1, 12, 30, 0, 0, time::UTC.clone());
let d2 = time::Date(2000, 2, 1, 20, 30, 0, 0, beijing);///
let datesEqualUsingEqualOperator = d1 == d2;
let datesEqualUsingFunction = d1.Equal(&d2);
assert_eq!(false,datesEqualUsingEqualOperator);
assert_eq!(true,datesEqualUsingFunction);
println!("datesEqualUsingEqualOperator = {}",datesEqualUsingEqualOperator);
println!("datesEqualUsingFunction = {}", datesEqualUsingFunction);§Output:
datesEqualUsingEqualOperator = false
datesEqualUsingFunction = trueSourcepub fn IsZero(&self) -> bool
pub fn IsZero(&self) -> bool
IsZero reports whether t represents the zero time instant, January 1, year 1, 00:00:00 UTC.
zh-cn
IsZero报告t是否代表零点时刻,1年1月1日,00:00:00 UTC。Sourcepub fn Add(&mut self, d: &Duration) -> Time
pub fn Add(&mut self, d: &Duration) -> Time
Add returns the time t+d.
zh-cn
Add返回时间点t+d。§Example
use gostd_time as time;
use time::Duration;
let mut start = time::Date(2009, 1, 1, 12, 0, 0, 0, time::UTC.clone());
let afterTenSeconds = start.Add(&Duration::new(time::Second * 10));
let afterTenMinutes = start.Add(&Duration::new(time::Minute * 10));
let afterTenHours = start.Add(&Duration::new(time::Hour * 10));
let afterTenDays = start.Add(&Duration::new(time::Hour * 24 * 10));
println!("start = {}", start);
println!("start.Add(time.Second * 10) = {}", afterTenSeconds);
println!("start.Add(time.Minute * 10) = {}", afterTenMinutes);
println!("start.Add(time.Hour * 10) = {}", afterTenHours);
println!("start.Add(time.Hour * 24 * 10) = {}", afterTenDays);
Sourcepub fn Sub(&self, u: &mut Time) -> Duration
pub fn Sub(&self, u: &mut Time) -> Duration
Sub returns the duration t-u. If the result exceeds the maximum (or minimum) value that can be stored in a Duration, the maximum (or minimum) duration will be returned. To compute t-d for a duration d, use t.Add(-d).
zh-cn
返回一个时间段t-u。如果结果超出了Duration可以表示的最大值/最小值,将返回最大值/最小值。要获取时间点t-d(d为Duration),可以使用t.Add(-d)。§Example
Sourcepub fn Date(&self) -> (int, Month, int)
pub fn Date(&self) -> (int, Month, int)
Date returns the year, month, and day in which self occurs.
zh-cn
返回时间点self对应的年、月、日。§Example
use gostd_time as time;
let d = time::Date(2000, 2, 1, 12, 30, 0, 0, time::UTC.clone());
let (year, month, day) = d.Date();
assert_eq!((2000, time::Month::February, 1), d.Date());
println!("year = {}", year);
println!("month = {}", month);
println!("day = {}", day);§Output:
year = 2000
month = February
day = 1Sourcepub fn Month(&self) -> Month
pub fn Month(&self) -> Month
Sourcepub fn Clock(&self) -> (int, int, int)
pub fn Clock(&self) -> (int, int, int)
Clock returns the hour, minute, and second within the day specified by self.
zh-cn
Clock返回由self指定的一天中的时、分、秒。Sourcepub fn Hour(&self) -> int
pub fn Hour(&self) -> int
Hour returns the hour within the day specified by self, in the range [0, 23].
zh-cn
Hour 返回由self指定的一天中的第几小时,范围为[0, 23]。Sourcepub fn Minute(&self) -> int
pub fn Minute(&self) -> int
Minute returns the minute offset within the hour specified by self, in the range [0, 59].
zh-cn
Minute 返回由self指定的小时内的第几分钟,范围为[0, 59]。Sourcepub fn Second(&self) -> int
pub fn Second(&self) -> int
Second returns the second offset within the minute specified by self, in the range [0, 59].
zh-cn
Second 返回由self指定的分钟内的第几秒,范围为[0, 59]。Sourcepub fn Nanosecond(&self) -> int
pub fn Nanosecond(&self) -> int
Nanosecond returns the nanosecond offset within the second specified by t, in the range [0, 999999999].
zh-cn
Nanosecond 返回self对应的那一秒内的纳秒偏移量,范围[0, 999999999]。Sourcepub fn Truncate(&self, d: Duration) -> Time
pub fn Truncate(&self, d: Duration) -> Time
Truncate returns the result of rounding t down to a multiple of d (since the zero time). If d <= 0, Truncate returns t stripped of any monotonic clock reading but otherwise unchanged.
Truncate operates on the time as an absolute duration since the zero time; it does not operate on the presentation form of the time. Thus, Truncate(Hour) may return a time with a non-zero minute, depending on the time’s Location.
zh-cn
Truncate返回将t四舍五入到d的倍数的结果(从零开始)。如果d<=0,Truncate返回t,去除任何单调时钟读数,但在其他方面保持不变。Truncate将时间作为自零时间起的绝对持续时间进行操作;它在当时的表现形式上不起作用。因此,Truncate(Hour)可能返回非零分钟的时间,具体取决于时间的位置。
§Example
use gostd_builtin::*;
use gostd_time as time;
let t = time::Parse("2006 Jan 02 15:04:05", "2012 Dec 07 12:15:30.918273645")
.ok()
.expect("Parse failed");
let round: Vec<int64> = vec![
time::Nanosecond,
time::Microsecond,
time::Millisecond,
time::Second,
2 * time::Second,
time::Minute,
10 * time::Minute,
time::Hour,
];
for i in round {
let d = time::Duration::new(i);
println!(
"t.Truncate({}) = {}",
d,
t.Truncate(d).Format("15:04:05.999999999")
)
}
§Output:
t.Truncate(1ns) = 12:15:30.918273645
t.Truncate(1µs) = 12:15:30.918273
t.Truncate(1ms) = 12:15:30.918
t.Truncate(1s) = 12:15:30
t.Truncate(2s) = 12:15:30
t.Truncate(1m0s) = 12:15:00
t.Truncate(10m0s) = 12:10:00
t.Truncate(1h0m0s) = 12:00:00Sourcepub fn Round(&self, d: Duration) -> Time
pub fn Round(&self, d: Duration) -> Time
Round returns the result of rounding t to the nearest multiple of d (since the zero time). The rounding behavior for halfway values is to round up. If d <= 0, Round returns self stripped of any monotonic clock reading but otherwise unchanged.
Round operates on the time as an absolute duration since the zero time; it does not operate on the presentation form of the time. Thus, Round(Hour) may return a time with a non-zero minute, depending on the time’s Location.
zh-cn
返回距离self最近的时间点,该时间点应该满足从Time零值到该时间点的时间段能整除d;如果有两个满足要求的时间点,距离self相同,会向上舍入;如果d <= 0,会返回self的拷贝。§Example
use gostd_builtin::*;
use gostd_time as time;
let t = time::Date(0, 0, 0, 12, 15, 30, 918273645, time::UTC.clone());///
let round: Vec<int64> = vec![
time::Nanosecond,
time::Microsecond,
time::Millisecond,
time::Second,
2 * time::Second,
time::Minute,
10 * time::Minute,
time::Hour,
];
for i in round {
let d = time::Duration::new(i);
println!(
"t.Round({}) = {}",
d,
t.Round(d).Format("15:04:05.999999999")
)
}§Output:
t.Round(1ns) = 12:15:30.918273645
t.Round(1µs) = 12:15:30.918274
t.Round(1ms) = 12:15:30.918
t.Round(1s) = 12:15:31
t.Round(2s) = 12:15:30
t.Round(1m0s) = 12:16:00
t.Round(10m0s) = 12:20:00
t.Round(1h0m0s) = 12:00:00Sourcepub fn YeayDay(&self) -> int
pub fn YeayDay(&self) -> int
YearDay returns the day of the year specified by t, in the range [1, 365] for non-leap years, and [1, 366] in leap years.
zh-cn
YearDay 返回时间点self对应的那一年的第几天,平年的返回值范围`[1, 365]`,闰年`[1, 366]`。Sourcepub fn Weekday(&self) -> Weekday
pub fn Weekday(&self) -> Weekday
Sourcepub fn ISOWeek(&self) -> (int, int)
pub fn ISOWeek(&self) -> (int, int)
ISOWeek returns the ISO 8601 year and week number in which t occurs. Week ranges from 1 to 53. Jan 01 to Jan 03 of year n might belong to week 52 or 53 of year n-1, and Dec 29 to Dec 31 might belong to week 1 of year n+1.
zh-cn
ISOWeek 返回时间点t对应的ISO 9601标准下的年份和星期编号。星期编号范围[1,53],1月1号到1月3号可能属于上一年的最后一周,12月29号到12月31号可能属于下一年的第一周。Sourcepub fn UTC(&mut self) -> Time
pub fn UTC(&mut self) -> Time
UTC returns self with the location set to UTC.
zh-cn
UTC返回采用UTC和零时区,但指向同一时间点的Time。Sourcepub fn Local(&mut self) -> Time
pub fn Local(&mut self) -> Time
Local returns t with the location set to local time.
zh-cn
Local 返回采用本地和本地时区,但指向同一时间点的Time。Sourcepub fn In(&mut self, loc: Location) -> Time
pub fn In(&mut self, loc: Location) -> Time
In returns a copy of t representing the same time instant, but with the copy’s location information set to loc for display purposes.
In panics if loc is nil.
zh-cn
In 返回采用loc指定的地点和时区,但指向同一时间点的Time。如果loc为nil会panic
Sourcepub fn Location(&self) -> Location
pub fn Location(&self) -> Location
Location returns the time zone information associated with self.
zh-cn
Location 返回与self相关的时区信息。Sourcepub fn Zone(&self) -> (string, int)
pub fn Zone(&self) -> (string, int)
Zone computes the time zone in effect at time self, returning the abbreviated name of the zone (such as “CET”) and its offset in seconds east of UTC.
zh-cn
Zone计算t所在的时区,返回该时区的规范名(如"CET")和该时区相对于UTC的时间偏移量(单位秒)。Sourcepub fn Unix(&self) -> int64
pub fn Unix(&self) -> int64
Unix returns t as a Unix time, the number of seconds elapsed since January 1, 1970 UTC. The result does not depend on the location associated with t. Unix-like operating systems often record time as a 32-bit count of seconds, but since the method here returns a 64-bit value it is valid for billions of years into the past or future.
zh-cn
Unix将t作为Unix时间返回,即从1970年1月1日UTC开始经过的秒数。类似Unix的操作系统通常将时间记录为32位的秒数,但由于这里的方法返回的是64位的值,所以对过去或未来的数十亿年都有效。§Example
use gostd_time as time;
let t = time::Date(2001, 9, 9, 1, 46, 40, 0, time::UTC.clone());
println!("{}",t.Unix()); // seconds since 1970
println!("{}",t.UnixNano()); // nanoseconds since 1970
assert_eq!(1000000000,t.Unix());
assert_eq!(1000000000000000000,t.UnixNano());
§Output:
1000000000
1000000000000000000Sourcepub fn UnixMilli(&self) -> int64
pub fn UnixMilli(&self) -> int64
UnixMilli returns self as a Unix time, the number of milliseconds elapsed since January 1, 1970 UTC.
zh-cn
UnixMilli返回self作为Unix时间,即从1970年1月1日UTC开始经过的毫秒数。Sourcepub fn UnixMicro(&self) -> int64
pub fn UnixMicro(&self) -> int64
UnixMicro returns t as a Unix time, the number of microseconds elapsed since January 1, 1970 UTC.
zh-cn
UnixMicro将t作为Unix时间返回,即从1970年1月1日UTC开始经过的微秒数。Sourcepub fn UnixNano(&self) -> int64
pub fn UnixNano(&self) -> int64
UnixNano returns t as a Unix time, the number of nanoseconds elapsed since January 1, 1970 UTC.
zh-cn
UnixNano返回t作为Unix时间,即从1970年1月1日UTC开始经过的纳秒数。Sourcepub fn AddDate(&self, years: int, months: int, days: int) -> Time
pub fn AddDate(&self, years: int, months: int, days: int) -> Time
AddDate returns the time corresponding to adding the given number of years, months, and days to t. For example, AddDate(-1, 2, 3) applied to January 1, 2011 returns March 4, 2010.
AddDate normalizes its result in the same way that Date does, so, for example, adding one month to October 31 yields December 1, the normalized form for November 31.
zh-cn
AddDate返回与给定的年、月、日数相加的时间。例如,AddDate(-1, 2, 3)应用于2011年1月1日,返回2010年3月4日。AddDate以与Date相同的方式对其结果进行规范化处理,因此,例如,在10月31日的基础上增加一个月,得到12月1日,即11月31日的规范化形式。
§Example
use gostd_time as time;
let start = time::Date(2009, 1, 1, 0, 0, 0, 0, time::UTC.clone());
let oneDayLater = start.AddDate(0, 0, 1);
let oneMonthLater = start.AddDate(0, 1, 0);
let oneYearLater = start.AddDate(1, 0, 0);
assert_eq!(oneDayLater.String(), "2009-01-02 00:00:00 +0000 UTC");
assert_eq!(oneMonthLater.String(), "2009-02-01 00:00:00 +0000 UTC");
assert_eq!(oneYearLater.String(), "2010-01-01 00:00:00 +0000 UTC");
println!("oneDayLater: start.AddDate(0, 0, 1) = {}", oneDayLater);
println!("oneMonthLater: start.AddDate(0, 1, 0) = {}", oneMonthLater);
println!("oneYearLater: start.AddDate(1, 0, 0) = {}", oneYearLater);Source§impl Time
impl Time
Sourcepub fn AppendFormat(&self, b: Vec<byte>, layout: &str) -> Vec<byte> ⓘ
pub fn AppendFormat(&self, b: Vec<byte>, layout: &str) -> Vec<byte> ⓘ
AppendFormat is like Format but appends the textual representation to b and returns the extended buffer.
zh-cn
AppendFormat与Format类似,但将文本表示法追加到b,并返回扩展的缓冲区。§Example
use gostd_builtin::*;
use gostd_time as time;
let t = time::Date(2017, 11, 4, 11, 0, 0, 0, time::UTC.clone());
let mut text: Vec<byte> = "Time: ".as_bytes().to_vec();
text = t.AppendFormat(text, time::Kitchen);
assert_eq!("Time: 11:00AM", string(&text));
println!("{}", string(&text))§Output:
Time: 11:00AM