Sunday, July 11, 2021

Junior Developer Central JS Practice Exercise - 04

 
Question: 

Write a Javascript program to get the current date

Output:

mm-dd-yyyy
mm/dd/yyyy
dd-mm-yyyy
dd/mm/yyyy




Answer: 

function formatDate () {

let date = new Date(); 
let day = date.getDate(); 
let month = date.getMonth() + 1; 
let year = date.getFullYear(); 
let opt1 = `${month}-${day}-${year}`;
let opt2 = `${month}/${day}/${year}`;
let opt3 = `${day}-${month}-${year}`;
let opt4 = `${day}/${month}/${year}`;

console.log(opt1);
console.log(opt2);
console.log(opt3);
console.log(opt4);

};




> we declare a function 'formatDate'
> it has no parameters
> we declare various variables and initialize it with different type of date objects and methods
>> 'date' = new Date ();   ===>>> this will return the date object as it is a constructor
>> 'day' = date.getDate(); ===>>> this method will return the day of the month
>> 'month' = date.getMonth(); ===>>> this method will return the month (0 to 11)
        we shall add 1 as January is 0, February is 1 and so on
>> 'year' = date.getFullYear(); ===>>> this method returns the year
> we then use template literals and save them in different variables as we have multiple outputs
> finally we console log the variables to get our desired output of date in different formats

No comments:

Post a Comment