code.vegaprotocol.io/vega@v0.79.0/core/vegatime/time.go (about) 1 // Copyright (C) 2023 Gobalsky Labs Limited 2 // 3 // This program is free software: you can redistribute it and/or modify 4 // it under the terms of the GNU Affero General Public License as 5 // published by the Free Software Foundation, either version 3 of the 6 // License, or (at your option) any later version. 7 // 8 // This program is distributed in the hope that it will be useful, 9 // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 // GNU Affero General Public License for more details. 12 // 13 // You should have received a copy of the GNU Affero General Public License 14 // along with this program. If not, see <http://www.gnu.org/licenses/>. 15 16 package vegatime 17 18 import ( 19 "time" 20 21 types "code.vegaprotocol.io/vega/protos/vega" 22 ) 23 24 // Unix create a new time from sec and nsec in UTC timezone. 25 func Unix(sec int64, nsec int64) time.Time { 26 return time.Unix(sec, nsec).UTC() 27 } 28 29 // UnixNano equivalent to time.Unix(sec, nsec) but to be used with the 30 // result of time.Time{}.UnixNano() in UTC timezone. 31 func UnixNano(nsec int64) time.Time { 32 return time.Unix(nsec/int64(time.Second), nsec%int64(time.Second)).UTC() 33 } 34 35 // Parse parse a string expected to be a time in the time.RFC3339Nano format. 36 func Parse(t string) (time.Time, error) { 37 return time.ParseInLocation(time.RFC3339Nano, t, time.UTC) 38 } 39 40 // Format format the time using the time.RFC3339Nano formatting. 41 func Format(t time.Time) string { 42 return t.In(time.UTC).Format(time.RFC3339Nano) 43 } 44 45 // RoundToNearest round an actual time to the nearest interval. 46 func RoundToNearest(t time.Time, interval types.Interval) time.Time { 47 switch interval { 48 case types.Interval_INTERVAL_I1M: 49 return time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), 0, 0, time.UTC) 50 case types.Interval_INTERVAL_I5M: 51 return time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), (t.Minute()/5)*5, 0, 0, time.UTC) 52 case types.Interval_INTERVAL_I15M: 53 return time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), (t.Minute()/15)*15, 0, 0, time.UTC) 54 case types.Interval_INTERVAL_I1H: 55 return time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), 0, 0, 0, time.UTC) 56 case types.Interval_INTERVAL_I6H: 57 return time.Date(t.Year(), t.Month(), t.Day(), (t.Hour()/6)*6, 0, 0, 0, time.UTC) 58 case types.Interval_INTERVAL_I1D: 59 return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.UTC) 60 default: 61 return t 62 } 63 }