I have an angular application integrated with REST API developed with golang, on this app I have created a todo list functionality where I create todo for weekly or monthly, while creating todo I generate first timestamp with javascript and then submits it to API which created timestamp for other dates if its weekly or monthly todo. First timestamp is showing proper date time when I get it with API and show in using javascript date functions but other date's timestamps shows next day like if I save Wednesday then it shows Thursday.
As far as I know timestamps are not based on timezones so I chose timestamp instead of datetime
How can I resolve the issue ?
Following is my code to convert timestamp to date ( in required format )
let date = new Date(this.date*1000);
this.day = ("0" + date.getDate()).slice(-2);
this.month = ("0" + (date.getMonth()+1)).slice(-2);
this.year = date.getFullYear();
this.hours = ("0" + date.getHours()).slice(-2);
this.minutes = ("0" + date.getMinutes()).slice(-2);
this.seconds = ("0" + date.getSeconds()).slice(-2);
this.meridian = this.hours >= 12 ? 'pm' : 'am';
//Get name of the day and month
this.weekName = this.weekday[date.getDay()];
this.monthName = date.toLocaleString(this.locale, { month: "short" });
First off: I assume that this.weekday
is an array containing the names of the week like this:
this.weekday = [
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
"saturday",
"sunday"
]
This is a common way that people use to get the days of the week, but there are better ways.
Using toLocaleDateString
Vanilla Javascript has a nice way to get the name of the day and it even supports different locales!
this.weekName = this.date.toLocaleDateString('en', { weekday: 'long' })
Using an array with names
If for some reason you wish to use an array anyway, you should know that arrays are zero-based and date.getDay()
1-based. In other words: your array counts from 0 to 6, while date.getDay()
counts from 1 to 7.
A simple way to get around this, is just adding 1
to the result of date.getDay()
this.weekName = this.weekday[date.getDay() + 1];
The rest of your variables can also be set using Date.toLocaleDateString
, since it supports a lot of different outputs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getDay