Code Examples In JavaScript
Introduction
Date and time management is a crucial aspect of many web applications, whether scheduling events, logging user activity, or displaying localized times for a global audience.
JavaScript provides powerful tools for handling dates, times, Unix timestamps, and timezones, enabling developers to work seamlessly with time-related data.
The Date object in JavaScript serves as the foundation for date and time operations, offering methods to create, manipulate, and format dates and times.
For more advanced tasks like timezone handling, libraries such as Moment.js, date-fns, or the built-in Intl.DateTimeFormat API come in handy.
Get Current Time
Obtaining the current time is a fundamental task in web development, JavaScript makes it simple to retrieve and work with the current date and time using the built-in Date object.
The Date object provides several methods to get the current date and time in various formats, whether as a complete timestamp, individual components (year, month, day, etc.), or as a Unix timestamp.
Method:
1// Create a new Date object, representing the current date and time
2new Date()
Example:
1// Get the current date and time
2const now = new Date();
3
4console.log("Current date and time:", now);
5console.log("Year:", now.getFullYear()); // Current year
6console.log("Month:", now.getMonth() + 1); // Month (0-based, so add 1)
7console.log("Day:", now.getDate()); // Day of the month
8console.log("Hours:", now.getHours()); // Current hour
9console.log("Minutes:", now.getMinutes()); // Current minute
10console.log("Seconds:", now.getSeconds()); // Current second
11console.log("Milliseconds:", now.getMilliseconds()); // Milliseconds
12
13// Get the day of the week
14const daysOfWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
15console.log("Day of the week:", daysOfWeek[now.getDay()]);
Result:
1Current date and time: 2024-12-03T14:12:03.686Z
2Year: 2024
3Month: 12
4Day: 3
5Hours: 22
6Minutes: 12
7Seconds: 3
8Milliseconds: 686
9Day of the week: Tuesday
Get Unix Timestamp
Unix timestamps are a standard way of representing time as the number of seconds (or milliseconds) elapsed since the Unix epoch, which is January 1, 1970, at 00:00:00 UTC. They are widely used in web development for logging, scheduling, and synchronizing time across systems due to their simplicity and consistency.
JavaScript provides straightforward methods to obtain Unix timestamps using the built-in Date object. These timestamps are often returned in milliseconds, making them suitable for high-precision applications. Developers can easily convert these values to seconds or other formats as needed.
Method:
1// Returns the number of milliseconds elapsed since the epoch
2Date.now()
3
4// Using Date object
5const now = new Date();
6const timestampMilliseconds = now.getTime(); // Milliseconds
Example:
1// Get the current Unix timestamp in milliseconds
2const timestampMilliseconds = Date.now();
3console.log("Unix timestamp (milliseconds):", timestampMilliseconds);
4
5// Get the current Unix timestamp in seconds
6const timestampSeconds = Math.floor(timestampMilliseconds / 1000);
7console.log("Unix timestamp (seconds):", timestampSeconds);
8
9// Using Date object
10const now = new Date();
11const timestampMillisecondsUsingDate = now.getTime(); // Milliseconds
12const timestampSecondsUsingDate = Math.floor(now.getTime() / 1000); // Seconds
13
14console.log("Unix timestamp (milliseconds) using Date object:", timestampMillisecondsUsingDate);
15console.log("Unix timestamp (seconds) using Date object:", timestampSecondsUsingDate);
Result:
1Unix timestamp (milliseconds): 1733236284052
2Unix timestamp (seconds): 1733236284
3Unix timestamp (milliseconds) using Date object: 1733236284055
4Unix timestamp (seconds) using Date object: 1733236284
Construct New Time
Creating new date and time objects is a fundamental task, JavaScript’s Date object provides powerful tools to construct and manipulate date and time values with precision and flexibility.
You can easily construct new Date objects in JavaScript by specifying different parameters, such as year, month, day, hour, minute, second, and millisecond.
Additionally, JavaScript supports creating Date objects from strings or Unix timestamps, making it versatile for handling various formats and use cases.
Method:
1new Date()
2new Date(value)
3new Date(dateString)
4new Date(dateObject)
5
6// Note: The month is 0-based (January is 0, December is 11)
7new Date(year, monthIndex)
8new Date(year, monthIndex, day)
9new Date(year, monthIndex, day, hours)
10new Date(year, monthIndex, day, hours, minutes)
11new Date(year, monthIndex, day, hours, minutes, seconds)
12new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds)
Example:
1const now = new Date();
2console.log("Current date and time:", now);
3
4const specificDate = new Date(2023, 11, 3, 14, 30, 0, 0); // Dec 3, 2023, 14:30:00
5console.log("Specific date and time:", specificDate);
6
7const isoDate = new Date("2023-12-03T14:30:00Z");
8console.log("ISO date:", isoDate);
9
10const timestampDate = new Date(1701601800000); // Timestamp for Dec 3, 2023, 14:30:00 UTC
11console.log("Date from timestamp:", timestampDate);
Result:
1Current date and time: 2024-12-03T14:37:33.108Z
2Specific date and time: 2023-12-03T06:30:00.000Z
3ISO date: 2023-12-03T14:30:00.000Z
4Date from timestamp: 2023-12-03T11:10:00.000Z
Convert Unix timestamp to Readable Date Time
Unix timestamps, representing the number of seconds since the Unix epoch (January 1, 1970, at 00:00:00 UTC), are commonly used in programming for their simplicity and efficiency.
However, they are not human-readable, making it necessary to convert them into a readable date and time format for display, logging, or reporting purposes
JavaScript provides powerful tools for converting Unix timestamps into human-readable Date objects. With methods like toISOString(), toLocaleString(), and custom formatting techniques, you can transform timestamps into formats that suit your application’s needs
Method:
1new Date(timestampMilliseconds)
2date.toString()
3date.toLocaleDateString()
4date.toISOString()
5
6// using third party library "date-fns"
7// install using "npm install date-fns"
8// import { format } from 'date-fns';
9format(date, 'yyyy-MM-dd HH:mm:ss');
Example:
1import { format } from 'date-fns';
2
3const timestampMilliseconds = 1701601800000;
4const date = new Date(timestampMilliseconds);
5console.log("Readable date and time:", date.toString());
6console.log("Readable date and time in local format:", date.toLocaleDateString());
7console.log("ISO format:", date.toISOString());
8
9const formattedDate = format(date, 'yyyy-MM-dd HH:mm:ss');
10console.log("Formatted date:", formattedDate);
Result:
1Readable date and time: Sun Dec 03 2023 11:10:00 GMT+0000 (Coordinated Universal Time)
2Readable date and time in local format: 12/3/2023
3ISO format: 2023-12-03T11:10:00.000Z
4Formatted date: 2023-12-03 19:10:00
Convert Date Time to Unix timestamp
Converting date and time values to Unix timestamps is a common task in JavaScript, often required when working with APIs, databases, or time-based calculations.
JavaScript’s Date object makes it straightforward to convert human-readable dates into Unix timestamps. Whether you are working with the current time or a specific date, you can easily extract the timestamp in milliseconds using the getTime() method. If you need the timestamp in seconds, a simple conversion can be applied.
Method:
1new Date(dateString)
2
3// using third party library "date-fns"
4// install using "npm install date-fns"
5// import { parseISO } from 'date-fns';
6parseISO(dateString)
Example:
1import { parseISO } from 'date-fns';
2
3// Specify date in ISO 8601 format
4const date = new Date('2024-11-04T12:00:00Z');
5const timestamp = Math.floor(date.getTime() / 1000); // Convert to seconds
6console.log("Unix timestamp using Date object:", timestamp);
7
8// Convert an ISO date string to a Unix timestamp
9const parsedDate = parseISO('2024-11-04T12:00:00Z'); // Parse the date string
10// Convert to Unix timestamp in seconds
11const Parsedtimestamp = Math.floor(parsedDate.getTime() / 1000);
12console.log("Unix timestamp using parsedDate:", Parsedtimestamp);
Result:
1Unix timestamp using Date object: 1730721600
2Unix timestamp using parsedDate: 1730721600
Change Time Zone
Timezones play a critical role in applications that work with global users or time-sensitive data across different regions.
JavaScript provides tools for managing timezones, such as the built-in Date object and the Intl.DateTimeFormat API. These tools allow you to retrieve, format, and display times in various timezones.
For advanced timezone manipulation, libraries like Luxon, Moment.js, or date-fns-tz offer additional functionality, making it easier to work with timezones effectively.
Method:
1// Using Native JavaScript
2new Intl.DateTimeFormat(locales, options)
3
4// using third party library "date-fns-tz"
5// install using "npm install date-fns-tz"
6// import { format } from 'date-fns-tz';
7format()
8// import { formatInTimeZone } from 'date-fns-tz';
9formatInTimeZone()
Example:
1import { format, formatInTimeZone } from 'date-fns-tz';
2import { enGB } from 'date-fns/locale/en-GB';
3
4const date = new Date('2024-10-04T12:00:00Z'); // Example UTC date
5const formatter = new Intl.DateTimeFormat('en-US', {
6 timeZone: 'America/New_York',
7 year: 'numeric',
8 month: '2-digit',
9 day: '2-digit',
10 hour: '2-digit',
11 minute: '2-digit',
12 second: '2-digit',
13});
14console.log("Date using Intl.DateTimeFormat:", formatter.format(date));
15
16const timeZone = 'Europe/London';
17// Format the date in the target time zone
18const formattedDate = format(date, 'yyyy-MM-dd HH:mm:ssXXX', { timeZone });
19console.log("Date using format:", formattedDate);
20
21// Using formatInTimeZone
22const parisDate = formatInTimeZone(date, 'Europe/Paris', 'yyyy-MM-dd HH:mm:ss zzz', { locale: enGB })
23console.log("Date using formatInTimeZone:", parisDate);
Result:
1Date using Intl.DateTimeFormat: 10/04/2024, 08:00:00 AM
2Date using format: 2024-10-04 20:00:00+01:00
3Date using formatInTimeZone: 2024-10-04 14:00:00 CEST
Time Addition and Subtraction
Manipulating dates and times is a common requirement in many applications. With JavaScript, you can perform date and time addition or subtraction by working with Unix timestamps (milliseconds since the Unix epoch) or by manipulating individual components such as days, hours, and minutes.
Method:
1// Native JavaScript
2date.setDate()
3date.setXxx()
4
5// using third party library "date-fns"
6// install using "npm install date-fns"
7add();
8sub();
9differenceInSeconds(date2, date1);
Example:
1const date = new Date('2024-10-04T12:00:00Z'); // Example UTC date
2console.log('Original Date:', date);
3
4// Add 7 days
5const addDays = new Date(date);
6addDays.setDate(date.getDate() + 7);
7console.log('Add 7 Days:', addDays);
8
9// Subtract 3 hours
10const subtractHours = new Date(date);
11subtractHours.setHours(date.getHours() - 3);
12console.log('Subtract 3 Hours:', subtractHours);
13
14
15// Time add, sub, date-fns approach
16import { add, sub } from 'date-fns';
17
18console.log('Original Date Using date-fns:', date);
19
20// Add 3 hours
21const addHours = add(date, { hours: 3 });
22console.log('Add 3 Hours:', addHours);
23
24// Subtract 7 days
25const subtractDays = sub(date, { days: 7 });
26console.log('Subtract 7 Days:', subtractDays);
27
28// Add multiple units
29const addComplex = add(date, { days: 2, hours: 5, minutes: 30 });
30console.log('Add 2 Days, 5 Hours, 30 Minutes:', addComplex);
31
32
33// Time Difference, native javascript approach
34const date1 = new Date('2024-10-04T12:00:00');
35const date2 = new Date('2024-10-04T14:45:30');
36
37const differenceInMs = date2 - date1; // Difference in milliseconds
38console.log('Time Difference in milliseconds:', differenceInMs);
39
40
41// Time Difference, date-fns approach
42import { differenceInMilliseconds } from 'date-fns';
43
44const date3 = new Date('2024-09-04T12:00:00');
45const date4 = new Date('2024-10-04T14:45:30');
46
47console.log('Time Difference in milliseconds using date-fns:', differenceInMilliseconds(date4, date3));
Result:
1Original Date: 2024-10-04T12:00:00.000Z
2Add 7 Days: 2024-10-11T12:00:00.000Z
3Subtract 3 Hours: 2024-10-04T09:00:00.000Z
4Original Date Using date-fns: 2024-10-04T12:00:00.000Z
5Add 3 Hours: 2024-10-04T15:00:00.000Z
6Subtract 7 Days: 2024-09-27T12:00:00.000Z
7Add 2 Days, 5 Hours, 30 Minutes: 2024-10-06T17:30:00.000Z
8Time Difference in milliseconds: 9930000
9Time Difference in milliseconds using date-fns: 2601930000
Pause or sleep for a specific time
Pausing or delaying the execution of a program is a common requirement in various applications, such as implementing retries, creating animations, scheduling tasks, or rate-limiting requests.
Unlike some programming languages with built-in sleep functions, JavaScript achieves delays using asynchronous mechanisms like setTimeout and setInterval.
Method:
1// No build-in sleep function, use Promise to simulate
2new Promise(resolve => setTimeout(resolve, ms));
Example:
1function sleep(ms) {
2 return new Promise(resolve => setTimeout(resolve, ms));
3}
4
5async function main() {
6 console.log("Start");
7
8 // Sleep for 1 second
9 await sleep(1000);
10
11 console.log("End");
12}
13
14main();
Result:
1Start
2End