|
| 1 | +/* 9. Dates |
| 2 | +
|
| 3 | +Note: Our declared Dates has been calculated from 1 January 1970. |
| 4 | +Note: Dates has been calculated usually in Milliseconds. */ |
| 5 | + |
| 6 | +let myDate = new Date(); |
| 7 | +console.log(myDate); /* Output: 2024-04-24T08:15:11.671Z |
| 8 | +
|
| 9 | +-------------------------------------------------------------------------------------- |
| 10 | +
|
| 11 | +Conversion of Dates in readable form, |
| 12 | +Some Methods, */ |
| 13 | +console.log(myDate.toString()); // Output: Wed Apr 24 2024 13:47:36 GMT+0530 (India Standard Time) |
| 14 | +console.log(myDate.toDateString()); // Output: Wed Apr 24 2024 |
| 15 | +console.log(myDate.toLocaleString()); // Output: 24/4/2024, 1:49:14 pm |
| 16 | +console.log(myDate.toJSON()); // Output: 2024-04-24T08:20:04.530Z |
| 17 | +console.log(myDate.toISOString()); // Output: 2024-04-24T08:21:49.915Z |
| 18 | +console.log(myDate.toLocaleDateString()); /* Output: 24/4/2024 |
| 19 | +
|
| 20 | +-------------------------------------------------------------------------------------- |
| 21 | +
|
| 22 | +Typeof Date, */ |
| 23 | +console.log(typeof myDate); /* Output: Object |
| 24 | +
|
| 25 | +-------------------------------------------------------------------------------------- |
| 26 | +
|
| 27 | +Declaring a new or a specific date, */ |
| 28 | +// let myCreatedDate = new Date(2002, 10, 24) // Months starts with 0 in JS. |
| 29 | +// console.log(myCreatedDate.toDateString()); // Output: Sun Nov 24 2002 |
| 30 | +// let myCreatedDate = new Date(2002, 10, 24, 5, 3) |
| 31 | +// console.log(myCreatedDate.toLocaleString()); // Output: 24/11/2002, 5:03:00 am |
| 32 | +let myCreatedDate = new Date("11-24-2002") |
| 33 | +console.log(myCreatedDate.toLocaleString()); /* Output: 24/11/2002, 5:30:00 am |
| 34 | +
|
| 35 | +-------------------------------------------------------------------------------------- */ |
| 36 | + |
| 37 | +let myTimeStamp = Date.now() |
| 38 | +console.log(myTimeStamp); // Output: 1713948664801 (Millisecond value from 1 Jan 1970 to current) |
| 39 | +console.log(myCreatedDate.getTime()); /* Output: 1038076200000 |
| 40 | +So now we can easily compare 1713948664801 and 1038076200000. |
| 41 | +
|
| 42 | +Converting it into seconds, */ |
| 43 | +console.log(Math.floor(Date.now()/1000)); // Output: 1713950199 |
| 44 | + |
| 45 | +let myDates = new Date() |
| 46 | +console.log(myDates); |
| 47 | +console.log(myDates.getDay()); // Output: 3 |
| 48 | +console.log(myDates.getMonth() + 1); /* Output: 4 |
| 49 | +
|
| 50 | +---------------------------------------------------------------------------------------- |
| 51 | +
|
| 52 | +Some other syntax, */ |
| 53 | +`${myDates.getDay()} and the time is` |
| 54 | +// We can completely define what we want, |
| 55 | +myDates.toLocaleString('default', { |
| 56 | + weekday: "long" |
| 57 | +}) |
| 58 | + |
| 59 | + |
| 60 | + |
| 61 | + |
0 commit comments