Basics
JS Dates
Working with JavaScript Dates
JavaScript dates use Date objects, handling timezones cautiously.
Creating Date Objects
In JavaScript, dates are handled using the Date
object. You can create a new Date
object using the new Date()
constructor. There are several ways to initialize a date object, including:
- Without arguments, creating a date with the current date and time.
- With a date string.
- With date and time components as numbers.
Date Methods
The Date
object provides numerous methods for getting and setting date values:
getFullYear()
- Returns the year.getMonth()
- Returns the month (0-11).getDate()
- Returns the day of the month (1-31).getDay()
- Returns the day of the week (0-6).getHours()
,getMinutes()
,getSeconds()
- Return the respective time components.
Handling Timezones
JavaScript handles timezones using the local timezone of the environment where the script is executed. The Date
object automatically adjusts for daylight saving time and other timezone quirks.
To handle timezones explicitly, consider using the Date
methods that deal with UTC, such as getUTCHours()
, getUTCMinutes()
, etc., or leverage libraries like Moment.js or date-fns for more complex timezone manipulations.
Formatting Dates
JavaScript offers limited built-in options for formatting dates. The toLocaleDateString()
and toLocaleTimeString()
methods allow you to format dates and times according to the user's locale, providing a more human-readable format.
Basics
- Introduction
- Where To
- Output
- Syntax
- Comments
- Variables
- Scope
- Hoisting
- Errors
- Data Types
- Operators
- Ternary Operator
- Short-Circuit Evaluation
- If Else
- Switch
- Loops
- For...Of/For...In
- Functions
- this Keyword
- Objects
- Arrays
- Strings
- Template Literals
- Numbers
- Number Properties
- Dates
- Math
- Booleans
- Type Conversion
- Destructuring
- Spread/Rest
- RegExp
- Strict Mode
- Modules
- Security Basics
- Debugging
- Best Practices
- Mistakes
- Performance
- Reserved Words
- Sets
- Maps
- Bitwise
- Array Const
- Previous
- Number Properties
- Next
- Math