0

I have referred to the link javascript getTime() to 10 digits only. And I got to know the way to convert date to 10 digit timestamp. My requirement is that I want last month date timestamp. Below is the code that I have tried:

var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
var monthLastDay = Math.floor(lastDay.getTime()/1000);
console.log(monthLastDay);

When I run above code I get output: 1527705000. And when I check the output on https://www.unixtimestamp.com/index.php. I got

1527705000
Is equivalent to:
05/30/2018 @ 6:30pm (UTC)

Which I think is not correct as the month 05 has 31 days. So I should timestamp as 05/31/2018.

EDIT:

If I try with below code:

var date = new Date('6/8/2018');
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
var monthLastDay = Math.floor(lastDay.getTime()/1000);
console.log(monthLastDay);

I get output: 1530297000 which is equal to 6/29/2018. But output should be 6/30/2018.

Let me know possible solution to get the correct 10 digit timestamp.

Nah
  • 1,690
  • 2
  • 26
  • 46
Tavish Aggarwal
  • 1,020
  • 3
  • 22
  • 51

1 Answers1

1

I guess the problem is with your timezone.

> new Date('6/8/2018')
Fri Jun 08 2018 00:00:00 GMT+0200 (CEST)
> new Date('6/8/2018').getTime()
1528408800000 // which is 06/07/2018 @ 10:00pm (UTC)

You should build the date in UTC if you want to use the timestamp as is

> var date = new Date('6/8/2018');
> Date.UTC(date.getFullYear(), date.getMonth() + 1, 0);
1530316800000 // which is 06/30/2018 @ 12:00am (UTC)
Francesco
  • 4,052
  • 2
  • 21
  • 29