Time in Seconds Since Start of Day?

Viewed 464

Here's one way to get the number seconds since start of day:

package main

import (
	"fmt"
	"time"
)

func main() {
	now := time.Now()
	startOfDay := now.Truncate(24 * time.Hour)
	diffInSeconds := now.Sub(startOfDay).Truncate(1 * time.Second).Seconds()
	fmt.Println(diffInSeconds)
}

Is this approach ok – or is there a better way?

1 Answers

I recommend asking https://gemini.google.com/

I used the prompt "How can I improve this code: PASTED_CODE" and got this back.


The provided code is well-written and accomplishes calculating the number of secondscelapsed since the start of the current day. Here are some minor improvements you could consider:

Descriptive Variable Names:

  • While now and startOfDay are clear enough, you could use currentTime and beginningOfDay for even better readability.

Simplifying Calculation:

  • You can directly calculate the difference in seconds using now.Sub(startOfDay).Seconds(). This avoids the need for an extra .Truncate(1 * time.Second) call, which doesn't affect the final result since Seconds() already converts the duration to floating-point seconds.

Here's the revised code:

package main

import (
	"fmt"
	"time"
)

func main() {
	currentTime := time.Now()
	beginningOfDay := currentTime.Truncate(24 * time.Hour)
	secondsElapsed := currentTime.Sub(beginningOfDay).Seconds()
	fmt.Println(secondsElapsed)
}

These changes make the code slightly more concise and easier to understand without altering the functionality.