Skip to content

Instantly share code, notes, and snippets.

@meetzaveri
Last active September 26, 2020 13:11
Show Gist options
  • Save meetzaveri/12f99c340bf6ab4593239de5f0cbf301 to your computer and use it in GitHub Desktop.
Save meetzaveri/12f99c340bf6ab4593239de5f0cbf301 to your computer and use it in GitHub Desktop.
Utility scripts for dayjs. Shows how to get timestamp, date string and formatted data from dayjs library

To get timestamp

dayjs().valueOf()
// 1598941800000

// OR

dayjs(`${selectedTime.year}-${selectedTime.month}-${dateValue}`).valueOf()
// 1598941800000

To supply dynamic date,month and year and achieve timestamp

dayjs(2020-09-01).valueOf()
// 1598941800000

To get date string (replica to date instance returned for new Date())

dayjs().toDate()
// Tue Sep 01 2020 12:00:00 GMT+0530 (India Standard Time)

// OR (for specific date)
dayjs(2020-09-01).toDate()
//  Tue Sep 01 2020 12:30:00 GMT+0530 (India Standard Time) 

// OR (dynamically pass values and obtain timestamp)
dayjs(`${selectedTime.year}-${selectedTime.month}-${dateValue}`).toDate()
// Tue Sep 01 2020 12:30:00 GMT+0530 (India Standard Time) 

To get data for specific timezone

dayjs().tz('Asia/Kolkata').toDate()
// Tue Sep 01 2020 12:30:00 GMT+0530 (India Standard Time) 
 
// OR

dayjs(`${selectedTime.year}-${selectedTime.month}-${dateValue}`).tz('Asia/Kolkata')

To convert one timestamp to another OR to retreive timestamp value in specific timezone

  • get selected date,month and year and pass it into
 const currentTimeStamp = dayjs(
      `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
    )
      .tz('Asia/Kolkata')
      .hour(0)
      .minute(0)
      .valueOf();
    const lastDayOfCurrentMonth = dayjs(
      `${date.getFullYear()}-${date.getMonth() + 2}-${date.getDate()}`
    )
      .tz('Asia/Kolkata')
      .hour(0)
      .minute(0)
      .valueOf();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment