Coding JAVASCRIPT

Understanding Date and Time in JavaScript

Date and Time in JavaScript

Introduction

The date and time area unit a daily a part of our everyday lives and thus feature conspicuously in programming. In JavaScript, you would possibly need to produce a website with a calendar, a train schedule, or Associate in Nursing interface to line up appointments.

These applications have to be compelled to show relevant times supported the user’s current time zone, or perform calculations around arrivals and departures or begin and finish times.

You would possibly have to be compelled to use JavaScript to get a report at a precise time on a daily basis or filter through presently open restaurants and institutions.

To bring home the bacon all of those objectives and additional, JavaScript comes with the in-built Date object and connected ways. the way to format and use date and time in JavaScript.

Date Object

It stores date and time content. A built-in object in JS. It provides a variety of constitutional ways for data formatting and managing that knowledge.

Default, a brand new Date instance while not arguments provided creates Associate in Nursing object appreciate the present date and time. This may be created in keeping with the present computer’s system settings.

To demonstrate JavaScript’s Date, let’s produce a variable and assign the present date to that. this text is being written on Wed, Oct eighteenth in London (GMT), so is that the current date, time, and timezone that’s depicted below.

now.js
// Set variable to current date and time
const now = new Date();

// View the output
now;

Output

Wed Oct 18 2017 12:41:34 GMT+0000 (UTC)

Looking at the output, we have a date string containing the following:

Day of the Week Month Day Year Hour Minute Second TimeZone
Wed Oct 18 2017 12 41 34 GMT+0000 (UTC)

The date and time are choppy and written during an approach that we are able to perceive as humans.

JavaScript, however, understands the date supported a timestamp derived from the operating system time, that could be a price consisting of the number of milliseconds that have passed since the time of day on Jan first, 1970. we are able to get the timestamp with the getTime() technique.

// Get the current timestamp now.getTime();

Output:

1508330494000

The sizable amount that seems in our output for the present timestamp represents constant price as higher than, Oct eighteenth, 2017

Epoch time, conjointly noted as zero time, is depicted by the date string 01 Jan 1970 00:00:00 Greenwich Mean Time (UTC), and by the zero timestamps. we are able to take a look at this within the browser by making a brand new variable and distribution to that a brand new Date instance supported a timestamp of zero.

epoch.js
// Assign the timestamp 0 to a new variable
const epochTime = new Date(0);

epochTime;

Output:

01 January, 1970 00:00:00 Universal Time (UTC)

Epoch time was chosen as a typical for computers to live time by in earlier days of programming, and it’s the tactic that JavaScript uses.

READ  C Programming for Write a program to print all permutations of a given string

It is very important to grasp the construct of each the timestamp and therefore the date string, as each is also used betting on the settings Associate in Nursing purpose of an application.

So far, we have a tendency to learned the way to produce a brand new Date instance supported the present time, and the way to make one supported a timestamp.

In total, there area unit four formats by that you’ll be able to produce a brand new Date in JavaScript. Additionally, to the present time default and timestamp, you’ll be able to conjointly use a date string, or specify specific dates and times.

Creates date based on milliseconds since Epoch time creates date based on date string creates date based on specified date and time

 

Date Creation Output
new Date() Current date and time
new Date(timestamp) Creates date based on milliseconds since Epoch time
new Date(date string) Creates date based on date string
new Date(year, month, day, hours, minutes, seconds, milliseconds) Creates date based on specified date and time

To demonstrate the various ways in which to see a selected date, we’ll produce new Date objects which will represent Gregorian calendar month fourth, 1776 at 12:30 pm universal time in 3 other ways.

usa.js
// Timestamp method
new Date(-6106015800000);

// Date string method
new Date("January 31 1980 12:30");

// Date and time method
new Date(1776, 6, 4, 12, 30, 0, 0);

The 3 examples especially produce a date containing identical info

  • You’ll notice the timestamp methodology includes a negative variety; any date before Epoch time are pictured as a negative number
  • In the date and time methodology, our seconds and milliseconds square measure set to zero. If any variety is missing from the Date creation, it’ll default to zero. However, the order can’t be modified, thus keep that in mind if you opt to depart off variety.
  • You may notice that the month of the Gregorian calendar month is pictured by half dozen, not the standard seven. this can be as a result of the date and time numbers begin from zero, as the most tally in programming will. See consecutive section for an additional careful chart.

Retrieving the Date with get

  • Once we’ve got a date, we will access all the parts of the date with numerous integral strategies. The strategies can come back every a part of the date relative to the native timezone. Each of those strategies starts with get, and can come back the relative variety. Below may be a careful table of the get strategies of the Date object.
READ  C programming - Check if a graph is strongly connected
Date/Time Method Range Example
Year getFullYear() YYYY 1970
Month getMonth() 0-11 0 = January
Day (of the month) getDate() 1-31 1 = 1st of the month
Day (of the week) getDay() 0-6 0 = Sunday
Hour getHours() 0-23 0 = midnight
Minute getMinutes() 0-59
Second getSeconds() 0-59
Millisecond getMilliseconds() 0-999
Timestamp getTime() Milliseconds since Epoch time
  • Let’s make a new date, based on July 31, 1980, and assign it to a variable.
harryPotter.js
// Initialize a new birthday instance
const birthday = new Date(1980, 6, 31);
  • Now we can use all our methods to get each date component, from year to millisecond.
getDateComponents.js
birthday.getFullYear();      // 1980
birthday.getMonth();         // 6
birthday.getDate();          // 31
birthday.getDay();           // 4
birthday.getHours();         // 0
birthday.getMinutes();       // 0
birthday.getSeconds();       // 0
birthday.getMilliseconds();  // 0
birthday.getTime();          // 333849600000 (for GMT)

Sometimes it should be necessary to extract solely a part of a date, and also the integral get strategies square measure the tool you’ll use to attain this.

For an example of this, we will take a look at this date against the day and month of Gregorian calendar month third to check whether or not it’s Gregorian calendar month third or not.

oct3.js
// Get today's date
const today = new Date();

// Compare today with October 3rd
if (today.getDate() === 3 && today.getMonth() === 9) {
  console.log("It's October 3rd.");
} else {
  console.log("It's not October 3rd.");
}

Output:

It's not October 3rd.
  • Since, at the time of writing, it is not Gregorian calendar month third, the console reflects that.
  • The integral Date strategies that begin with get permit the United States to access date parts that come back the amount related to what we tend to square measure retrieving from the instantiated object.

Modifying the Date with set

  • For all the get strategies that we tend to learn concerning on top of, there’s a corresponding set methodology. wherever get is employed to retrieve a selected element from a date, a set is employed to switch parts of a date. Below may be a careful chart of the set strategies of the Date object.
Date/Time Method Range Example
Year setFullYear() YYYY 1970
Month setMonth() 0-11 0 = January
Day (of the month) setDate() 1-31 1 = 1st of the month
Day (of the week) setDay() 0-6 0 = Sunday
Hour setHours() 0-23 0 = midnight
Minute setMinutes() 0-59
Second setSeconds() 0-59
Millisecond setMilliseconds() 0-999
Timestamp setTime() Milliseconds since Epoch time
READ  Top 10 White Hat Hackers 2017

We will use these set strategies to switch one, more, or all of the parts of a date. for instance, we will amend the year of our birthday variable from on top of to be 1997 rather than 1980.

harrypotter.js
// Change year of birthday date
birthday.setFullYear(1997);

birthday;

Output:

Thu Jul 31 1997 00:00:00 GMT+0000 (UTC)
  • We see within the example on top of that {when we tend to|once we|after we} decision the birthday variable we receive the yr as a part of the output.
  • The integral strategies starting with set allow us to modify totally different components of a Date object.

Date strategies with Greenwich Time

  • The get strategies mentioned on top of retrieving the date parts supported the user’s native timezone settings.
  • For increased management over the dates and times, you’ll use the get UTC strategies, that square measure precisely the same because the get strategies, except they calculate the time supported the Greenwich Time (Coordinated Universal Time) customary. Below may be a table of the Greenwich Time strategies for the JavaScript Date object.
Date/Time Method Range Example
Year getUTCFullYear() YYYY 1970
Month getUTCMonth() 0-11 0 = January
Day (of the month) getUTCDate() 1-31 1 = 1st of the month
Day (of the week) getUTCDay() 0-6 0 = Sunday
Hour getUTCHours() 0-23 0 = midnight
Minute getUTCMinutes() 0-59
Second getUTCSeconds() 0-59
Millisecond getUTCMilliseconds() 0-999
  • To test the difference between local and UTC get methods, we can run the following code.
UTC.js
// Assign current time to a variable
const now = new Date();

// Print local and UTC timezones
console.log(now.getHours());
console.log(now.getUTCHours());
  • Running this code can print out this hour, and also the hour of the Greenwich Time zone. If you square measure presently within the Greenwich Time timezone the numbers that are output from running the program on top of are identical.
  • UTC is helpful therein it provides a global time customary reference and may so keep your code consistent across timezones if that’s applicable to what you’re developing.

Conclusion

  • In this tutorial, we tend to learn a way to produce an instance of the Date object and use its integral strategies to access and modify parts of a selected date. For an additional in-depth read of dates and times in JavaScript, you’ll browse the Date reference on the Mozilla Developer Network.
  • Knowing a way to work with dates is important for several common tasks in JavaScript, as this may alter you to try to several things from fixing a continuation report back to displaying dates and schedules within the correct geographical zone.

About the author

Venkatesan Prabu

Venkatesan Prabu

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

Add Comment

Click here to post a comment