Junior
How can you work with dates in JavaScript?
sobes.tech AI
Answer from AI
JavaScript uses the built-in Date object for working with dates. It allows creating, formatting, parsing, and manipulating dates and times.
Examples of common operations:
// Creating dates
const now = new Date();
const specificDate = new Date('2024-06-01T12:00:00Z');
// Getting date components
console.log(now.getFullYear()); // year
console.log(now.getMonth()); // month (0-11)
console.log(now.getDate()); // day of month
// Setting components
now.setHours(15);
// Formatting
console.log(now.toISOString());
console.log(now.toLocaleString('ru-RU'));
// Parsing string to date
const parsedDate = new Date(Date.parse('2024-06-01T12:00:00Z'));
// Working with time zones requires additional libraries like Luxon or date-fns-tz
For more convenient date and time handling, third-party libraries are often used, which simplify formatting, parsing, and timezone manipulations.