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.

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

3 Answers3

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.

Dylan Landry
  • 1,150
  • 11
  • 27
  • While this is a useful comment, it's not an answer. A Date object isn't required, a [*replace* solution](https://stackoverflow.com/a/44493245/257182) is more efficient, less code and more robust. :-) – RobG Oct 15 '20 at 23:39
  • Why is it not an answer? – Dylan Landry Oct 16 '20 at 02:15
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);
Ruben Helsloot
  • 12,582
  • 6
  • 26
  • 49
  • `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?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Oct 15 '20 at 23:32
-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

Rudraprasad Das
  • 348
  • 1
  • 10
  • You should avoid the built–in parser, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/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. – RobG Oct 15 '20 at 23:49