DEV Community

Cover image for Mastering JavaScript Date and Time πŸ“†
Shivam Singh
Shivam Singh

Posted on • Updated on

Mastering JavaScript Date and Time πŸ“†

Welcome to Day 1 of "Pro Tips of JavaScript"!

Hey there! Ever wanted to make your website do cool things? That's where JavaScript comes in. It's a computer language that helps websites come alive!

Over the next 10 days, I'll give you helpful tips to get better at JavaScript. Whether you're a complete beginner or have used JavaScript before, these tips will make coding easier for you. Each day, we'll explore a new part of JavaScript, teaching you useful tricks and ways to solve common problems.

Each day, we'll talk about a new and exciting part of JavaScript. I promise to keep things fun and simple. So, are you ready? Let's dive in!


Absolutely, grab your seat belts and flex your space-time muscles, because we're about to get date-y. πŸ•ΊπŸ’ƒ

Greetings, future Masters of Time (or just JavaScript)! πŸ§™β€β™‚οΈπŸ’« Do you ever wish you could control time? No, I'm not talking about discovering the Infinity Stones or hitting 88 mph in a DeLorean. I mean JavaScript's Date and Time methods. Today we'll go over pro tips that'll make you the Time Lord of JavaScript! β°πŸ› οΈ


1. Converting to Human-Readable Strings

Ever get that date format that looks like your cat walked on your keyboard? Say hello to toLocaleString(), your savior!

Input

const date = new Date("2023-09-15T15:30:00Z");
Enter fullscreen mode Exit fullscreen mode

Output in Console

console.log(date.toLocaleString()); // "9/15/2023, 8:30:00 AM" (depends on your locale)
Enter fullscreen mode Exit fullscreen mode

So fancy, even James Bond would approve. πŸ‘Œ


2. Setting Specific Time πŸ”§β°

For those times you just need to seize the minute (or hour), the setHours and setMinutes methods have your back!

Input

const specificTime = new Date();
specificTime.setHours(12, 30, 0);
Enter fullscreen mode Exit fullscreen mode

Output in Console

console.log(specificTime); // Outputs a date with 12:30:00 time
Enter fullscreen mode Exit fullscreen mode

Why yes, that is tea time in England! 🍡


3. Milliseconds to Human Time β³πŸ‘¨β€πŸ’Ό

Milliseconds are great for machines but bad for your social life. Here's how you humanize them!

Input

const milliseconds = 980010000;
Enter fullscreen mode Exit fullscreen mode

Output in Console

console.log(`${Math.floor(milliseconds / (24 * 60 * 60 * 1000))} days`);
// "11 days"
Enter fullscreen mode Exit fullscreen mode

Wow, you're literally counting the days, huh? πŸ“…


4. Unix Timestamps 🌌⏰

Ever wondered what time it was at the exact moment Luke Skywalker learned Darth Vader was his father? Let's Unix-timestamp that!

Input

const starWarsMoment = new Date('1980-05-21T00:00:00Z');
Enter fullscreen mode Exit fullscreen mode

Output in Console

console.log(starWarsMoment.getTime()); // "326592000000"
Enter fullscreen mode Exit fullscreen mode

That’s a number bigger than Yoda's age! 🌌


5. Time Wizard πŸ§™πŸ“†

Ever tried to schedule a date only to find out you’ve double-booked because you forgot that JavaScript counts months from 0 (who does that, right?). You won't need a time-turner for this. Date math in JavaScript is like the Dark Arts, only less dark and more artsy.

Input

// Calculating the number of days between two dates
const date1 = new Date('2023-09-15');
const date2 = new Date('2023-09-20');
const diffTime = Math.abs(date2 - date1);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); 
Enter fullscreen mode Exit fullscreen mode

Output in Console

// The number of days between the two dates
console.log(diffDays);  // Output will be 5
Enter fullscreen mode Exit fullscreen mode

Did you ever think you'd be able to rip through the time-space continuum with Math.ceil() and Math.abs()? No, right? But look at you, mastering the fourth dimension like a Time Lord, or rather, a Date Lord! πŸ“†πŸ•°οΈ


6. Calculating Ages πŸŽ‚πŸ“…

Ever lied about your age on social media? Here's how to calculate it correctly.

Input

const birthDate = new Date('1995-02-14');
const age = ((new Date()).getFullYear() - birthDate.getFullYear());
Enter fullscreen mode Exit fullscreen mode

Output in Console

console.log(age); // Outputs "28" if it's 2023
Enter fullscreen mode Exit fullscreen mode

Now you can't lie! Unless you really want to. 😜


7. Checking Day or Night πŸŒ—πŸŒž

You ever wonder why your code isn't running? Maybe it's sleeping! Here's how to check the time of day.

Input

const now = new Date();
Enter fullscreen mode Exit fullscreen mode

Output in Console

console.log(now.getHours() >= 6 && now.getHours() <= 18 ? 'Day' : 'Night'); 
// Outputs "Day" or "Night"
Enter fullscreen mode Exit fullscreen mode

Look, your code is nocturnal! πŸ¦‰


8. Scheduling Future Dates with Date.now() ⏱️

Forget crystal balls. Here's how to peer into the future with Date.now().

Input

const futureTime = Date.now() + 1000 * 60 * 60 * 24;
Enter fullscreen mode Exit fullscreen mode

Output in Console

console.log(new Date(futureTime)); // Outputs a date 24 hours from now
Enter fullscreen mode Exit fullscreen mode

No DeLorean required! πŸš—


Conclusion

So you made it, Time Lords! πŸ•°οΈ You've traveled through the ins and outs of JavaScript Date and Time. What's your favorite new trick? Let me know in the comments below.πŸ‘‡πŸΌ

May your code always be timely, and may you never miss a deadline! 🌈πŸ’₯ Until next time, keep your timers ticking and your alarms alarming! 🚨


And that's how you earn your Time Lord degree in JavaScriptology! πŸŽ“ Feel free to jot down your temporal musings in the comments! πŸ‘‡

Top comments (1)

Collapse
 
ssdas_dev profile image
Shibaram Das

Thank you.