- Published on
Working with dates
- Authors
- Name
- Mathieu Sévégny
Important informations about JS/TS Dates
Thanks to this post from Stack Overflow
- When creating a new date, it can change depending on your timezone.
new Date("2011-09-24"); // Year-Month-Day
// => Fri Sep 23 2011 17:00:00 GMT-0700 (MST) - ONE DAY OFF.
- To get a correct date, we can :
- Use "/" instead of "-"
- Rearrange the date to MM-DD-YYYY
//Use "/" instead of "-"
new Date("2011/09/24"); // change from "-" to "/".
// => Sat Sep 24 2011 00:00:00 GMT-0700 (MST) - CORRECT DATE.
//Rearrange the date to MM-DD-YYYY
new Date("09-24-2011");
// => Sat Sep 24 2011 00:00:00 GMT-0700 (MST) - CORRECT DATE.
- Here is a technique to do the first one with code :
const date = "2022-02-19";
const dateInGoodFormat = date.replace(/-/g, '\/');
console.log(dateInGoodFormat)
// => "2022/02/19"
new Date(dateInGoodFormat)
// => 2022-02-19T05:00:00.000Z
Here are some of my most used functions when working with dates in TypeScript.
How to change a date to ISO format (YYYY-MM-DD)
function DateInISO(date:Date) : string {
//Adds a zero before the digit if the number is below 10
const conv = function(num:number) {
return (num < 10 ? '0' : '') + num;
};
return date.getFullYear() +
'-' + conv(date.getMonth() + 1) +
'-' + conv(date.getDate())
}
Calculate last Friday
- Firstly, I made an
enumto represent each day of the week.
enum Day{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
- After, I modified a function I found on Stack Overflow made by a user named
hazzik.
function getLast(dateOfWeek : Day,from?:Date) {
//If no date given, gives today.
if (!from) from = new Date();
const d = new Date(from)
const day = d.getDay()
const diff = (day <= dateOfWeek) ? (7 - dateOfWeek + day ) : (day - dateOfWeek);
d.setDate(d.getDate() - diff);
d.setHours(0);
d.setMinutes(0);
d.setSeconds(0);
return d
}
- We can now check which day was the last Friday from February 19, 2022
const lastFriday = getLast(Day.Friday, new Date("2022/02/19"))
console.log(DateInISO(lastFriday))
// => 2022-02-18