Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last day in month of time.Time

Tags:

time

go

When I have a time.Time:

// January, 29th
t, _ := time.Parse("2006-01-02", "2016-01-29")

How can I get a time.Time which represents January 31st? This example is trivial, but when there's a date in February, the last day might be 28th or 29th.

like image 527
Kiril Avatar asked Feb 03 '16 16:02

Kiril


People also ask

How do you find the first and last day of the current month?

To get the first and last day of the current month, use the getFullYear() and getMonth() methods to get the current year and month and pass them to the Date() constructor to get an object representing the two dates.

How do I get the last day of the month in Ruby?

new(y, m, d) , you can create a new Date object. The values for day (d) and month (m) can be negative in which case they count backwards from the end of the year and the end of the month respectively.


1 Answers

Package time

func Date

func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time

Date returns the Time corresponding to

yyyy-mm-dd hh:mm:ss + nsec nanoseconds

in the appropriate zone for that time in the given location.

The month, day, hour, min, sec, and nsec values may be outside their usual ranges and will be normalized during the conversion. For example, October 32 converts to November 1.

For example, normalizing a date,

package main

import (
    "fmt"
    "time"
)

func main() {
    // January, 29th
    t, _ := time.Parse("2006-01-02", "2016-01-29")
    fmt.Println(t.Date())
    // January, 31st
    y,m,_ := t.Date()
    lastday:= time.Date(y,m+1,0,0,0,0,0,time.UTC)
    fmt.Println(lastday.Date())
}

Output:

2016 January 29
2016 January 31
like image 182
peterSO Avatar answered Oct 12 '22 12:10

peterSO