How do I reformat the date from openweather api using javascript?

799 views Asked by At

How do I format the date I receive from openweather api? I currently get 2020-10-16 00:00:00 and I want 10-16-2020.

The reason I don't use moment is because I want future dates which come automatically with the 5 day forecast in the api.

3

There are 3 answers

2
Dylan Landry On

You can use JavaScript's Date object.

You might save yourself time by searching a bit more before posting a question, the answer is probably already out there.

1
Rudraprasad Das On

You can always use the built in Javascript Date object.

In your case you'd want to. do something like this -

const myDate = new Date('2020-10-16 00:00:00');
const date = myDate.getDate();
const month = myDate.getMonth() + 1;
const year = myDate.getFullYear();
console.log('MM-DD-YYYY', `${month}-${date}-${year}`);

If you want something more convinient and don't want to use moment you can also try some other popular date libraries. You can find some here - https://github.com/you-dont-need/You-Dont-Need-Momentjs

1
Nikola Chetelyazov On

You could try to:

  • Make a new date based on the date that comes from OpenWeather api
  • Convert it to a LocaleDateString using the 'en-US' locale. This will make the month appear before the date.
  • Then just split the Date String on the '/' and join in on a '-'. This will substitute the '/' with a '-'

const date = new Date("2020-10-16 00:00:00").toLocaleDateString('en-US');
const formatedDate = date.split('/').join('-');

console.log(formatedDate);