0

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.

1
  • '2020-10-16 00:00:00'.replace(/(\d{4})\-(\d{2})\-(\d{2}).*/, '$2-$3-$1'), no library or Date object required. Commented Oct 15, 2020 at 23:37

3 Answers 3

0

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.

Sign up to request clarification or add additional context in comments.

2 Comments

While this is a useful comment, it's not an answer. A Date object isn't required, a replace solution is more efficient, less code and more robust. :-)
Why is it not an answer?
0

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);

1 Comment

new Date("2020-10-16 00:00:00") returns an invalid Date in at least one current browser. See Why does Date.parse give incorrect results?
-1

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 Comment

You should avoid the built–in parser, see Why does Date.parse give incorrect results? It seems somewhat inefficient to parse the string to a Date just to use functions to get values that are available in the original string when split and replace can do that more efficiently and reliably without using a Date object.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.