Tri Nguyen Dung Tri Nguyen Dung - 3 months ago 11
Javascript Question

How to format database datetime in javascript?

I have a datetime value gotten from an SQLServer database table:

2016-08-16T17:00:00Z


Using javascript, I want to format the date as follow:

16/08/2016 17:00:00


I have used the code below:

$scope.FormatDate = function (value) {
if (value !== null && typeof (value) !== 'undefined') {
var date = new Date(value);
var returnStr = date.getDate() + "/" + date.getMonth() + 1 + "/" + date.getFullYear();
return returnStr;
} else {
return value;
}
}


The result from the sample resource is:

17/71/2016


I want your help to get the output result as: "16/08/2016 17:00:00"

Answer

If all you want to do is format it then you don't need to create an actual date object, you can do a simple string replace using a regex to grab the individual parts, as per this simple demo:

var value = "2016-08-16T17:00:00Z";
console.log(value.replace(/(\d{4})-(\d\d)-(\d\d)T([^Z]+)Z/,"$3/$2/$1 $4"));

In the context of your function:

$scope.FormatDate = function (value) {
  if (value !== null && typeof (value) !== 'undefined') {
    return value.replace(/(\d{4})-(\d\d)-(\d\d)T([^Z]+)Z/,"$3/$2/$1 $4");
  } else {
    return value;
  }
}
Comments