I like to start a series based on JavaScript which will have a collection of code snippets that will help to do a specific task. Each post will be related to one particular topic in JavaScript, I hope the snippets will help beginners to find ways to achieve certain tasks.
Here is the part one which consists of code snippets based on Date object in JavaScript. If you like to know more about time and dates you can use this.
1.Code to find yesterday: Method 1
// Find Yesterday Method 1
function getYesterday(){
let today = new Date();
let yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
console.log(`Today: ${today.toDateString()} Yesterday: ${yesterday.toDateString()}`);
}
getYesterday();
//Today: Tue May 18 2021 Yesterday: Mon May 17 2021
getDate() will return the current date, substracting one will give the yesterday's date as a number data type, when we provide the value to the setDate() method we get the yesterday's time/date info. Use toDateString() method to get the date part in string.
Code to find yesterday: Method 2
// Find Yesterday Method 2
const yesterday1 = (today1 => new Date(today1.setDate(today1.getDate() - 1)))(new Date);
console.log(yesterday1);
2.Code to find tomorrow: Method 1
// Find Tomorrow
function getTomorrow(){
let today = new Date();
let tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
console.log(`Today: ${today.toDateString()} Tomorrow: ${tomorrow.toDateString()}`);
}
getTomorrow();
//Today: Tue May 18 2021 Tomorrow: Wed May 19 2021
The method is same as finding yesterday the only difference is instead of substracting one from the getDate() value we add one to the value.
Code to find tomorrow: Method 2
const tomm1 = (today1 => new Date(today1.setDate(today1.getDate() + 1)))(new Date);
console.log(tomm1);
3.Code to print current day.
// Print Day
function printWeekday(){
let names = ['Sunday', 'Monday',
'Tuesday', 'Wednesday', 'Thursday',
'Friday', 'Saturday'];
console.log(`Today is ${names[new Date().getDay()]}`);
}
printWeekday();
//Today is Tuesday
getDay() method returns the current day in number form 0 to 6, where 0 represents Sunday. The value is used as the index of day names array which starts with Sunday at index 0.
4.Code to print current month
// Print Month
function printMonthName(){
let names = ['January', 'February', 'March', 'April', 'May',
'June','July', 'August', 'September', 'October',' November',
'December'];
console.log(`The month is ${names[new Date().getMonth()]}`);
}
printMonthName();
//The month is May
getMonth() method returns the current month in number form 0 to 11, where 0 represents January. The value is used as the index of array of month names which starts with January at index 0.
5.Code to print first and last day of month
// Get first and last day of month
function firstLastDay(year,month){
let dateFirst = new Date(year,month-1,1);
let dateLast = new Date(year,month,0);
console.log(dateFirst.toLocaleDateString(), dateLast.toLocaleDateString());
}
firstLastDay(2021, 1); // 1/1/2021 1/31/2021
firstLastDay(2021, 2); // 2/1/2021 2/28/2021
firstLastDay(2021, 5); // 5/1/2021 5/31/2021
To get the first day create a new Date object with year and month whose first day you want to get, remember month stars from 0 to 11, you can skip the date part or you can use one. If you need to know the last day create a new Date object with year, number representing the next month, and zero, since there is no date 0, the output will be the last day of previous month.
6.Code to print number of days in a month
// Print Number of days in a month
// Month starts from 0, so (year,month, 0) gives last day of month-1
function getDaysInMonth(year,month){
let days = new Date(year, month,0).getDate();
console.log(`Number of days in ${month}/${year}: ${days}`);
}
getDaysInMonth(2021, 1); // Number of days in 1/2021: 31
getDaysInMonth(2021, 2); // Number of days in 2/2021: 28
getDaysInMonth(2021, 5); // Number of days in 5/2021: 31
If you need to know the last day; create a new Date object with year, number representing the next month and zero, since there is no date of 0, the output will be the last day of previous month, get the date from the output using getDate() method.
7.Code to print time in AM/PM format
// Find AM or PM time in hh:mm:ss format
function amOrpm(t){
let time = t.split(" ")[0].split(':');
if(parseInt(time[0]) >= 12){
parseInt(time[0]) === 12 ? 12 : parseInt(time[0] % 12);
time.push("PM")
}else{
time.push("AM")
}
console.log(`${time[0]}:${time[1]}:${time[2]} ${time[3]}`);
}
amOrpm(new Date().toTimeString()); // 17:31:07 PM
To add AM/PM manually to time, first get the time part, split it when ':' is found, check the hour part, if the hour part is greater than or equal to twelve find the modulus of the hour value with 12 and add 'PM'. If the hour part is less than 12 append 'AM' to the value.
8.Code to calculate number of days between two dates
// Calculate number of days between two dates
function noDates(first, last){
let difference = Math.ceil((last - first) / (1000*60*60*24));
console.log(`The number of days between ${first.toLocaleDateString()} and ${last.toLocaleDateString()} is ${Math.abs(difference)} days`);
}
noDates(new Date('2018-1-1'), new Date('2021-05-15'))
//The number of days between 1/1/2018 and 5/15/2021 is 1231 days
In JavaScript Date objects are based on the milliseconds elapsed since 1st January 1970, so when we do arithmetic operations between dates the output will be in milliseconds. Here we try to find the difference between two dates, we get the difference as milliseconds, to convert that into dates we divide it with milliseconds equal to one day(24*60*60*24).
9.Code to calculate number of months between two dates
// Calculate number of months between two dates
function numMonths(first, last){
let yearToMonths = [last.getFullYear() - first.getFullYear()] * 12;
let months = [yearToMonths + (last.getMonth() + 1)] - (first.getMonth() + 1);
console.log(`Number of months between ${first.toLocaleDateString} and
${last.toLocaleDateString} is ${months}`);
}
numMonths(new Date('2018-05-21'), new Date('2021-05-21'));
// Number of months between 5/21/2018 and 5/21/2021 is 36
The number of dates between two days can be found by
- finding the difference in years between two dates
- multiply the difference with 12
- add the number of months in the recent date to it
- substract the number of months of second date from the value.
In the above method the days are not considered, while calculating the months, you can add more accuracy by considering the dates also.
Top comments (0)