TransWikia.com

need help displaying tomorrows date correctly, javascript

Stack Overflow Asked on December 23, 2021

For a project I’m working on I need a five day forecast. I’m starting out with tomorrow (which should be tomorrows date of whenever the user opens the app) and the date is appearing on the screen but it is formatted like this (Fri Jul 24 2020 22:40:10 GMT-0700 (Pacific Daylight Time)). What I would like is a format like this: Fri Jul 24.

Here is my javascript:

const tomorrow = new Date().format(ll) 

tomorrow.setDate(new Date().getDate() + 1);

one = document.getElementById('one');
one.innerHTML = tomorrow;

2 Answers

By using .toDateString() function you can get return of Fri Jul 24 2020.

Then you can delete the last 4 characters using substr.

Here is a simple example:

const tomorrow = new Date()
tomorrow.setDate(new Date().getDate() + 1)

console.log(tomorrow.toDateString())
// "Sat Jul 25 2020"
console.log(tomorrow.toDateString().substr(0, 10))
// "Sat Jul 25"

Answered by Nurul Huda on December 23, 2021

I would just use toLocaleDateString with the right options:

const formatDate = (d) => {
  const options = { weekday: 'short', month: 'short', day: 'numeric' };
  return d.toLocaleDateString("en-US", options).replace(',','');
}
const tomorrow = new Date()
tomorrow.setDate(new Date().getDate() + 1);
console.log(formatDate(tomorrow));
tomorrow.setDate(tomorrow.getDate() + 1);
console.log(formatDate(tomorrow));
tomorrow.setDate(tomorrow.getDate() + 1);
console.log(formatDate(tomorrow));

Answered by dave on December 23, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP