This question already has an answer here:
How to get specific time from next day
(1 answer)
Closed 2 years ago.
I want to get a datetime object for tomorrow morning 09:00 in Go. My current take is this:
now := time.Now()
tomorrowMorning := time.Date(now.Year(), now.Month(), now.Day(), 9, 0, 0, 0, time.UTC).AddDate(0, 0, 1))
It seems oddly verbose though. Isn't there a simpler way of doing this?
Simplify by adding 1 to the day directly.
now := time.Now()
tomorrowMorning := time.Date(now.Year(), now.Month(), now.Day() + 1, 9, 0, 0, 0, time.UTC)
Run it on the playground.
The time.Date function normalizes the day.
Related
This question already has answers here:
Go time.Time.UTC() sometimes gives 7 digits, sometimes 9
(1 answer)
prevent json.Marshal time.Time removing trailing zeros
(1 answer)
Closed 2 months ago.
I have a Go API that is supposed to return a timestamp in the following format (Java notation but should be understandable):
yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'
My Go API will build this timestamp as follows:
func ParseToTimestamp(duration string, systemTime time.Time) (string, error) {
parsedDuration, err := time.ParseDuration(duration)
if err != nil {
return "", err
}
validity := systemTime.Add(parsedDuration)
return validity.Format("2006-01-02T15:04:05.999999Z"), nil
}
I've noticed, however, that this formatted string is not always respecting the wished format. For example, if I pass a date which has 0 nano-seconds:
duration := "10m"
systemTime := time.Date(1990, time.January, 24, 0, 0, 0, 0, time.UTC) //no nano-seconds
timestamp, _ := fxcash.ParseToTimestamp(duration, systemTime)
fmt.Println(timestamp)
>> 1990-01-24T00:10:00Z
However, if I pass a date which has 120k nano-seconds:
duration := "10m"
systemTime := time.Date(1990, time.January, 24, 0, 0, 0, 120000, time.UTC) //120k nano-seconds
timestamp, _ := fxcash.ParseToTimestamp(duration, systemTime)
fmt.Println(timestamp)
>> 1990-01-24T00:10:00.00012Z
Generally speaking, this causes an issue because the service that consumes my Go output expects to have exactly 6 nano-seconds, even if they were only zeros .000000Z.
Is there a way to do that without heavy parsing/ugly splitting using standard Go Libraries?
Sorry if this question is basic but I'm very new to Go, I've looked for examples on the web but couldn't find any.
I was working on a project and wanted to add the difference in DateTime in terms of minutes, hours, days, weeks, months and years. I was able to get in minutes up to days. e.g.
DateTime.now().difference(DateTime(2019, 10, 7)).inDays
But I had a hard time creating it for weeks, months and years. How can I do so, please help
I constructed a package to help me with this called Jiffy
Jiffy([2018, 1, 29]).diff(Jiffy([2019, 10, 7]), Units.DAY); // -616
Jiffy([2018, 1, 29]).diff(Jiffy([2019, 10, 7]), Units.WEEK); // -88
Jiffy([2018, 1, 29]).diff(Jiffy([2019, 10, 7]), Units.MONTH; // -20
Jiffy([2018, 1, 29]).diff(Jiffy([2019, 10, 7]), Units.YEAR); // -1
you can calculate month diff size manually (without use any packege):
static int getMonthSizeBetweenDates(DateTime initialDate, DateTime endDate){
return calculateMonthSize(endDate)-calculateMonthSize(initialDate)+1;
}
static int calculateMonthSize(DateTime dateTime){
return dateTime.year*12+dateTime.month;
}
getMonthSizeBetweenDates method gives you how many months between your initial and end dates.
for example : your initial date is 1.1.2022 and your end date is 1.3.2022 .
then this method return 3 (january, fabruary and march)
You can find week and year diff bye using this logic.
Another method:
static int getMonthSizeBetweenDates2(DateTime initialDate, DateTime endDate){
return (endDate.year-initialDate.year)*12+(endDate.month-initialDate.month)+1;
}
There is a very simple and easy way to do this, and requires very little date/time arithmetic knowledge.
Simply compare both DateTimes' microsecondSinceEpoch values:
Duration compare(DateTime x, DateTime y) {
return Duration(microseconds: (x.microsecondsSinceEpoch - y.microsecondsSinceEpoch).abs())
}
DateTime x = DateTime.now()
DateTime y = DateTime(1994, 11, 1, 6, 55, 34);
Duration diff = compare(x,y);
print(diff.inDays);
print(diff.inHours);
print(diff.inMinutes);
print(diff.inSeconds);
The code above works, and works much more efficiently than conducting checks for leap-years and aberrational time-based anomalies.
To get larger units, we can just approximate. Most end-users are satisfied with a general approximation of this sort:
Weeks: divide days by 7 and round.
Months: divide days by 30.44 and round; if < 1, display months instead.
Years: divide days by 365.25 and floor, and also display months modulo 12.
I am using nrf52832 chip. I will be receiving time in isoFormat.
I am wondering how convert the iso format to get the date and time in my C program.
I am not using any RTOS but doing everything on baremetal.
Have asked the same question in nordic devzone:
https://devzone.nordicsemi.com/question/184631/handling-iso-datetime-in-nrf52/
We are going with the solution where we ill pass the isoTime as a string and convert that to time_t using the solution in:
https://cboard.cprogramming.com/c-programming/169114-how-convert-string-time_t.html
const char T[] = "2017-12-26T10:53:58.025905";
int year = 0, month = 0, day = 0, hour = 0, min = 0;
sscanf(T, "%4d-%2d-%2dT%2d:%2d", &year, &month, &day, &hour, &min);
Very new to the 'Go'. Question might be basic one.
I have two time.Time objects and I want to get the difference between the two in terms of hours/minutes/seconds. Lets say:
t1 = 2016-09-09 19:09:16 +0530 IST
t2 = 2016-09-09 19:09:16 +0530 IST
In above case, since the difference is 0. It should give me 00:00:00. Consider another case:
t1 = 2016-09-14 14:12:48 +0530 IST
t2 = 2016-09-14 14:18:29 +0530 IST
In this case, difference would be 00:05:41. I looked at the https://godoc.org/time but could not make anything out of it.
You may use Time.Sub() to get the difference between the 2 time.Time values, result will be a value of time.Duration.
When printed, a time.Duration formats itself "intelligently":
t1 := time.Now()
t2 := t1.Add(time.Second * 341)
fmt.Println(t1)
fmt.Println(t2)
diff := t2.Sub(t1)
fmt.Println(diff)
Output:
2009-11-10 23:00:00 +0000 UTC
2009-11-10 23:05:41 +0000 UTC
5m41s
If you want the time format HH:mm:ss, you may constuct a time.Time value and use its Time.Format() method like this:
out := time.Time{}.Add(diff)
fmt.Println(out.Format("15:04:05"))
Output:
00:05:41
Try the examples on the Go Playground.
Of course this will only work if the time difference is less than a day. If the difference may be bigger, then it's another story. The result must include days, months and years. Complexity increases significnatly. See this question for details:
golang time.Since() with months and years
The solution presented there solves this issue by showing a function with signature:
func diff(a, b time.Time) (year, month, day, hour, min, sec int)
You may use that even if your times are within 24 hours (in which case year, month and day will be 0).
Actually, the time package's documentation does discuss it:
https://godoc.org/time#Time.Sub
https://godoc.org/time#Duration.Hours
You should produce a Duration object using Sub() and then use one of the Seconds(), Minutes(), Hours().
package main
import (
"fmt"
"time"
)
func main() {
t1 := time.Date(1984, time.November, 3, 13, 0, 0, 0, time.UTC)
t2 := time.Date(1984, time.November, 3, 10, 0, 0, 0, time.UTC)
fmt.Printf("The hours difference is: %f", t1.Sub(t2).Hours())
}
To complement Shmulik Klein's answer:
Another way to calculate disjoint hours/minutes/seconds out of a time.Duration:
https://play.golang.org/p/VRoXG5NxLo
package main
import (
"fmt"
"math"
"time"
)
func main() {
t1 := time.Date(1984, time.November, 3, 13, 0, 0, 0, time.UTC)
t2 := time.Date(1984, time.November, 3, 10, 23, 34, 0, time.UTC)
hs := t1.Sub(t2).Hours()
hs, mf := math.Modf(hs)
ms := mf * 60
ms, sf := math.Modf(ms)
ss := sf * 60
fmt.Println(hs, "hours", ms, "minutes", ss, "seconds")
}
2 hours 36 minutes 25.999999999999375 seconds
note:
slight precision loss due to the use of the float64 type
we ignore leap seconds and assume every minute has 60 seconds
There are 2 common ways:
straight forward one:
startTime := time.Now()
diff := time.Now().Sub(startTime)
shorter one (a bit):
startTime := time.Now()
diff := time.Since(startTime)
DEMO
package main
import (
"fmt"
"math"
"time"
)
func TimeAsString(dt float64) string {
time := dt
hours := math.Floor(time / 3600)
minutes := math.Ceil(math.Mod(time, 3600)/60) - 1
seconds := int(time) % 60
return fmt.Sprintf("%v:%v:%v", hours, minutes, seconds)
}
func main() {
mytime := 0.0
last := time.Now()
tick := time.Tick(33 * time.Millisecond)
for {
select {
case <-tick:
dt := time.Since(last).Seconds()
last = time.Now()
mytime += dt
fmt.Println(TimeAsString(mytime))
}
}
}
I'm trying to get some sort of script working so It checks two files every 5 mins to check if they've updated/changed/been modified.
If file 1 has been updated/changed/been modified it should do one thing, if file 2 has been updated/changed/been modified it should close a certain program and launch a new program then change the programs title and move it to 0, 0 (top left of screen)
The part I don't know how to do is the checking the files to see if they've been updated/changed/been modified.
Could someone help me and point me in the right direction?
Thanks in advance :)
You are looking for FileGetTime, specifically with the option set to 0 (modified)
Code Example
Func Timecheck()
$file1_2 = FileGetTime("C:\file1.txt", 0, 1)
$file2_2 = FileGetTime("C:\file2.txt", 0, 1)
If $file1_1 == $file1_2 Then
; Do something here if file 1 isn't modified within 5ins
EndIf
If $file2_1 == $file2_2 Then
; Maybe WinClose?
WinClose("programhere")
; Maybe ProcessClose
ProcessClose("process.exe")
; Launch your program...
Run(...)
; Wait for process
ProcessWait("process.exe")
; Wait for Program...
WinWait("programhere")
WinSetTitle("programhere", "", "newprogramhere")
WinMove("newprogramheret", "", 0, 0, 800, 600, 1)
EndIf
$file1_1 = FileGetTime("C:\file1.txt", 0, 1)
$file2_1 = FileGetTime("C:\file2.txt", 0, 1)
EndFunc
; Initial Launch, grab current GetTime
$file1_1 = FileGetTime("C:\file1.txt", 0, 1)
$file2_1 = FileGetTime("C:\file2.txt", 0, 1)
While 1
Sleep(300000)
Timecheck()
WEnd
Reference: http://www.autoitscript.com/autoit3/docs/functions/FileGetTime.htm