1

I have a date string in such format: '11:29:16 01.08.2019'. I need to convert it to a date object, because it will be used to sort a table. For this purpose I use this code:

const myDate = '11:29:16 01.08.2019'
new Date(myDate + 'Z')

The problem is that the code interprets "01.08" as January 8, but it must be August 1.

Charlie
  • 22,886
  • 11
  • 59
  • 90

3 Answers3

0

If you just want it to be sortable, you don't really need to parse it.

Given that the date format is day.month.year you could just reformat the string to put the date first, after flipping the order of the date components.

const myDate = '11:29:16 01.08.2019';
const [time, date] = myDate.split(' ');

const sortableDate = date.split('.').reverse().join('-') + ' ' + time;
console.log(sortableDate);
phuzi
  • 12,078
  • 3
  • 26
  • 50
0

Use a date specialist such as moment.js

Just input the string and specify the format.

var d = moment("11:29:16 01.08.2019", "hh:mm:ss DD.MM.YYYY");
Charlie
  • 22,886
  • 11
  • 59
  • 90
-2

In your case. This will help you

function formateDate(myDate)
{
  var datearr=myDate.split(" ")[1].split(".");
  var timeStr=myDate.split(" ")[0];
  var dateObj=new Date(datearr[2]+"-"+datearr[1]+"-"+datearr[0]+"T"+timeStr+"Z");
  return dateObj;
}
console.log(formateDate('11:29:16 01.08.2019'));
Ravi
  • 1,312
  • 10
  • 18
  • It gives `Sep 01` instead of `Aug 1` as requested by OP – gkb Aug 06 '19 at 09:07
  • I had accepted it because it gives the general idea, it's not hard to correct this code to have what is needed. – Washington Irving Aug 06 '19 at 09:14
  • Code–only answers aren't that helpful. Parsing a string to create another string that is then parsed by the built–in parser seems inefficient, why not just pass the parts directly to the Date constructor and avoid the vagaries of the built–in parser? Also, the first string you create is sortable as text using *localeCompare* without being turned into a Date. – RobG Aug 07 '19 at 00:56