0

I'm getting 2019-09-10T00:00:00 as a response from API, So I want to remove the time part and want only 2019-09-10 as result.

$('<td>').text(item['Date']),
  $('<td>').text(item['Time In']),
$('<td>').text(item['Time Out'])

This is what my code is looking like, now I want to change these three.

str
  • 42,689
  • 17
  • 109
  • 127
Navneet Kumar
  • 623
  • 1
  • 6
  • 16

2 Answers2

2

Use split and split the date on 'T'

 var a='2019-09-10T00:00:00';
 console.log(a.split('T')[0])
ellipsis
  • 12,049
  • 2
  • 17
  • 33
1

You can make a bit generic solution i-e by working with date objects.

function formatDate(date, format ) {
  var dd = date.getDate();
  var mm = date.getMonth()+1; 
  var yyyy = date.getFullYear();
  
  if(dd<10) dd='0'+dd;
  if(mm<10) mm='0'+mm;

  switch(format) {
    case 'm-d-y': return mm+'-'+dd+'-'+yyyy;
    case 'm/d/y': return mm+'/'+dd+'/'+yyyy;
    case 'd-m-y': return dd+'-'+mm+'-'+yyyy;
    case 'd/m/y': return dd+'/'+mm+'/'+yyyy;
    default: return mm+'-'+dd+'-'+yyyy;
  }
}

const d = '2019-09-10T00:00:00';
console.log(formatDate(new Date(d), 'm/d/y'));
Faraz Javed
  • 154
  • 6
  • Given that this is just reordering of numbers that are already available in the original string, why use a Date object? And if that was to be the solution, there are already many questions and answers on [how to format a date](https://stackoverflow.com/search?q=%5Bjavascript%5D+how+to+format+a+date). – RobG Sep 10 '19 at 11:44
  • lets say you get "2019-09-10 10:00 AM" as a date, in this scenario, the accepted answer will fail. And if we get the date string as "2019-11-1T00:00:00", the solution you proposed will be failed as well. ('2019-09-10T00:00:00'.substr(0,10)) – Faraz Javed Sep 10 '19 at 13:55
  • Your answer will fail with `new Date("2019-11-1T00:00:00")` too. See [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) But that's not the OP format. – RobG Sep 10 '19 at 20:43