JavaScript LocaleDateString back to Date Object

1k views Asked by At

INTRODUCTION

I have a DatePicker component that returns a JS Native Date Object. When the user selects a date, I automatically convert it to a locale date string, just for making it visible in a text input. Every single text input in my app has a function 'getText()' to get their values... so I need to get this locale date string and convert it back to a native js Date object.

This has to work for every country.

Here is a representation of what I am trying to do:

enter image description here

PROBLEM

I have tried to do new Date(localeDateStr) but doesn't work as expected because the Date object doesn't accept date formats like "DD/MM/YYYY". Any ideas how to handle this?

I would really appreciate your help. Thank you.

Pd: I am using js-joda and native date methods from JS. Also, the react framework.

JS-Joda has a method "LocaleDate.parse(dateStr)" which accept string of the type 'mm-dd-yyyy' so it doesn't work for my use case.

2

There are 2 answers

2
Krzysztof Safjanowski On BEST ANSWER

The d object could store both values that can be retrieved by toString() and valueOf() methods, something like:

d = {
toString(): d.toLocaleDateString(),
valueOf(): d.getTime()
}

For representation / render purpose - toString() will be called implicit, for mathematical - valueOf(). You could e.g multiply d by 1 before sending through API

0
Vidhya J On

Convert LocaleDateString back to Date in JavaScript:

I have explained conversion without using moment.js in javascript

1.For string format,"DD/MM/YYYY"

String date="24/06/2022";
var arr = date.split("/");
let dateObj= new Date(parseInt(arr[2]);
parseInt(arr[1]),parseInt(arr[0])); //new Date(int year,int Month,int day)

2.For String Format , "MMM-yyyy"

String date="Aug-2021";  
var arr = reviewDate.split("-");  
var months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
let month = months.indexOf(arr[0].toLowerCase());
let dateObj= new Date(parseInt(arr[1]), month);

Below code works only to convert string which are in ISO 8601 standards like YYYY-MM-DD or YYYY/MM/DD else it prints as invalid date

let dateObj=new Date("");