المعرفة::JavaScript الحالة::مؤرشفة المراجع:: The Complete JavaScript Course 2022 From Zero to Expert, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Date Object
- JavaScript
Date
objects represent a single moment in time in a platform-independent format.Date
objects contain aNumber
that represents milliseconds since 1 January 1970 UTC.
Creating Dates
Current (now) Date
From date string
From date and time component values
- Month is zero based.
- JavaScript auto-corrects wrong month days.
From Unix epoch timestamp
- Value passed here is the number of milliseconds since January 1, 1970, 00:00:00 UTC.
Working with dates
getFullYear()
: returns the year of the specified date according to local time.getMonth()
: returns the month in the specified date according to local time, as a zero-based value.getDate()
: returns the day of the month for the specified date according to local time.getDay()
: returns the day of the week for the specified date according to local time, where 0 represents Sunday.getHours()
,getMinutes()
,getSeconds()
: returns the hours, minutes, and second for the specified date, according to local time.getTime()
: returns the number of milliseconds since the ECMAScript epoch.toISOString()
: returns a string in simplified extended ISO format (YYYY-MM-DDTHH:mm:ss.sssZ
or±YYYYYY-MM-DDTHH:mm:ss.sssZ
)setFullYear()
,setMonth()
,setDate()
,setMonth()
,setMinutes()
,setSeconds()
,setMilliseconds()
.
Getting now date in DD/MM/YYYY format
Operations on dates
Converting a date to number
Calculate days between two dates
- Using
Math.abs
it can deal with any case whether date 1 is later or the opposite. - To convert timestamp to days: (1000 milliseconds to seconds 60 seconds 60 minutes * 24 hours)
- For more complex calculations like handling daylight saving changes, we should use a library like moment.js.
Dates Internationalization
- The
Intl
object is the namespace for the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, and date and time formatting.
DateTimeFormat()
Intl.DateTimeFormat
object enables language-sensitive date and time formatting.- Locale parameter can be one of any ISO country language codes. See the list here.
- The date and time formats can be customized using the options argument.
Getting locale from user’s browser
- The
Navigator.language
read-only property returns a string representing the preferred language of the user, usually the language of the browser UI.