This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 15k traffic Daily!!!

Working With Javascript Date & Time: A Cheat Sheet


A standard activity in programming is working with date and time. Javascript Date object offers us with a wealth of strategies which might be fairly helpful and highly effective. However utilizing these strategies appropriately to get the specified outcome may be difficult.

So I picked essentially the most regularly used strategies and put them into this cheat sheet to make your life simpler.



Desk of Contents




An Overview

When working with dates and occasions, you may most definitely wish to carry out addtions/subtractions in your date or time values, remodel a price from one sort, e.g. quantity to a different, e.g. string, format your date and time strings and so forth.

For instance, for instance we wish a string illustration of the time quarter-hour from now. We comply with these steps to get the outcome:

  1. Get the variety of milliseconds (nowMs) for now.
  2. Add 15 * 60 * 1000 to nowMs (fifteenMinutesLaterMs).
  3. Convert fifteenMinutesLaterMs to a time string.
  4. Optionally format the time string.

We’ll have a look at this instance in additional element later, however as you possibly can see, on the core of fixing such issues is knowing what information sorts you should carry out what operations and which strategies enable you obtain that.




Cheat Sheet

Here’s a listing of the strategies I discover I am utilizing more often than not. Please word that,

  • All strategies, besides the constructors new Date() and Date() and static methodology Date.now(), are occasion strategies of a Date object.
  • Variety of milliseconds refers back to the variety of milliseconds between January 1, 1970, 00:00:00 UTC and your specified date.
  • To seek out out extra in regards to the strategies, try MDN docs on Date.



Strategies returning Date object

Params: date object/date string/milliseconds/yr, month/yr, month, day/yr, month, day, hours/…



Strategies returning variety of milliseconds

  • Date.now()
  • getTime()
  • setTime(params)

Params: variety of milliseconds

Params: hours/hours, minutes/hours, minutes, seconds/hours, minutes, seconds, milliseconds

Params: minutes/minutes, seconds/minutes, seconds, milliseconds

Notice: For data on different setSometing() strategies, try MDN docs on Date.



Strategies returning date/time string

Returning each date and time in a single string

  • Date() (similar as new Date().toString())
  • toString()
  • toLocaleString(params)

Params (elective): locales/locales, options

Returning date string

  • toDateString()
  • toLocaleDateString(params)

Params: locales/locales, options

Returning time string

  • toTimeString()
  • toLocaleTimeString(params)

Params: locales/locales, options




Frequent Use Instances

Now, let’s take a look at some widespread use circumstances of those strategies. Please word the values used within the examples beneath are topic to my timezone and the time the date objects had been instantiated, so your values will most definitely be completely different.



Milliseconds to Date

Instance:
1670454321367 → 2022-12-07T23:05:21.367Z

Resolution:

const date = new Date(1670454321367)
Enter fullscreen mode

Exit fullscreen mode



String to Date

Instance:
‘2022-12-07’ → 2022-12-07T00:00:00.000Z
‘2022-12-07T00:00’ → 2022-12-06T15:00:00.000Z

Resolution:

const date1 = new Date('2022-12-07')
const date2 = new Date('2022-12-07T00:00')
Enter fullscreen mode

Exit fullscreen mode

Notice: Though the 2 strings handed to Date constructor appear to discuss with the identical date, two completely different dates had been returned within the instance. It’s because Date-only strings are treated as UTC, while date-time strings are treated as local.



12 months, Month, Day Numbers to Date

Instance:
2022, 11, 7 → 2022-12-06T15:00:00.000Z

Resolution:

const date = new Date(2022, 11, 7)
Enter fullscreen mode

Exit fullscreen mode

Notice: Bear in mind month is 0-based and the handed yr, month and day numbers are handled as native.



Date to Milliseconds

Example1: present date time
present date time → 1670454321367

Resolution:

const ms = Date.now()
Enter fullscreen mode

Exit fullscreen mode

Example2: specified date time
2022-12-07T21:00 → 1670414400000

Resolution:

const ms = new Date('2022-12-07T21:00').getTime()
// OR
const ms = new Date('2022-12-07').setHours(21, 0, 0)
Enter fullscreen mode

Exit fullscreen mode

Example3: specified time of as we speak
21:00 of as we speak → 1670414400000

Resolution:

const ms = new Date().setHours(21, 0, 0)
Enter fullscreen mode

Exit fullscreen mode



Date to String

Example1:
Wed Dec 07 2022 21:33:20 → ‘Wed Dec 07 2022 21:33:20 GMT+0900 (日本標準時)’

Resolution:

const str = Date()
// OR
const str = new Date().toString()
Enter fullscreen mode

Exit fullscreen mode

Example2:
Wed Dec 07 2022 21:33:20 → ‘2022/12/7 21:33:20’

Resolution:

const str = new Date().toLocaleString()
Enter fullscreen mode

Exit fullscreen mode

Example3:
Wed Dec 07 2022 21:33:20 → ‘Wed Dec 07 2022’

Resolution:

const str = new Date().toDateString()
Enter fullscreen mode

Exit fullscreen mode

Example4:
Wed Dec 07 2022 21:33:20 → ‘2022/12/7’

Resolution:

const str = new Date().toLocaleDateString()
Enter fullscreen mode

Exit fullscreen mode

Example5:
Wed Dec 07 2022 21:33:20 → ’21:33:20 GMT+0900 (日本標準時)’

Resolution:

const str = new Date().toTimeString()
Enter fullscreen mode

Exit fullscreen mode

Example6:
Wed Dec 07 2022 21:33:20 → ’21:33:20′

Resolution:

const str = new Date().toLocaleTimeString()
Enter fullscreen mode

Exit fullscreen mode



String to Milliseconds

Instance:
’21:00′ of as we speak → 1670414400000 (your output will probably be completely different)

Resolution:

const [h, m] = '21:00'.break up(':')
const ms = new Date().setHours(h, m, 0)
Enter fullscreen mode

Exit fullscreen mode



Milliseconds to string

Instance:
1670414400000 → ’21:00′

Resolution:

const ms = new Date(1670414400000).toLocaleTimeString().slice(0, -3)
Enter fullscreen mode

Exit fullscreen mode

Notice: For single-digit hours, say 8, toLocaleTimeString() returns 8:00:00 whereas toTimeString() returns 08:00:00. To get constant outcomes, I used slice(0, -3) to simply drop the final :00.



Get an Offset Time String

Instance:
‘8:00’ → ‘8:30’

Resolution:

const offsetMs = 30 * 60 * 1000
const timeBeforeMs = new Date().setHours(8, 0, 0)
const timeAfterMs = timeBeforeMs + offsetMs
const timeAfterString = new Date(timeAfterMs).toLocaleTimeString().slice(0, -3)
Enter fullscreen mode

Exit fullscreen mode




Conclusion

On this publish, we checked out a number of the most regularly used Javascript information time strategies. By enjoying with the parameters of these strategies, e.g. the choices parameter of toLocaleSomething() strategies, you may uncover that these strategies are literally extra highly effective than I demonstrated right here.

As I discussed, it is necessary to know what sort of knowledge you need and which strategies enable you get the right sort of knowledge. And as a bonus tip, I extremely advocate you NAME your variables in a approach that explicitly conveys details about the kind of information they maintain. This implies myTimeMs is a greater identify for a variable holding a milliseconds worth than myTime.

Lastly, if you’re undecided about any of the strategies, do try the nice MDN docs on Date.

The Article was Inspired from tech community site.
Contact us if this is inspired from your article and we will give you credit for it for serving the community.

This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 10k Tech related traffic daily !!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?