Reputation: 151
I am getting time like "DOB": "/Date(862588800000+0800)/" from json API but I have to convert it into something like Date Format : 04/28/2017 10:20:05 (MM/dd/yyyy HH:mm:sss) . Need help
Upvotes: 0
Views: 1225
Reputation: 159
For Eg:
{{document.lastUpdateDateTime | date:"MM/dd/yyyy h:mma" :'CST6CDT'}}
it will represent the date in MM/dd/yyyy h:mm:SSS format.
please go through this one.
https://angular.io/api/common/DatePipe
[https://www.prokerala.com/travel/timezones/CST6CDT][2]
<td>{{document.lastUpdateDateTime | date:"MM/dd/yyyy h:mma" :'CST6CDT'}}</td>
write a function inside a controller. .
$scope.getCSTDateTime= function(lastUpdateDateTime) {
var currentDate = new Date(lastUpdateDateTime);
console.log("Current Date is :" + currentDate);
var h = currentDate .getHours();
var mm = currentDate .getMinutes();
var SSS = currentDate .getSeconds();
//date:"MM/dd/yyyy h:mma" :'CDT'
var month = currentDate .getUTCMonth() + 1; //months from 1-12
var day = currentDate .getUTCDate();
var year = currentDate .getUTCFullYear();
return month + "/" + day + "/" +year +" "+h+":"+mm+":"+SSS;
};
Upvotes: 0
Reputation: 147473
You can start by parsing the value to a Date object, then formatting the output.
The first number part appears to be a time value that is milliseconds since the epoch (1970-01-01), followed by a timezone offset in HHMM. Time values before the epoch are negative, so a regular expression to get the parts might be:
/[+-]?\d+/g
which should match both the time value and the offset.
The time value can adjusted by the offset then used to create a Date (the value passed to the Date constructor needs to be a number, or it will be parsed as if it's a string):
function parseDate(s) {
// Get the parts
var b = s.match(/[+-]?\d+/g);
// If appears invalid, return invalid Date
if (!b || b.length != 2) return new Date(NaN);
// Get sign of offset
var sign = +b[1] < 0? -1 : 1;
// Convert offset to milliseconds
// Multiplication converts the strings to numbers so + adds
var offset = sign * b[1].substr(1,2)*3.6e6 + b[1].substr(3,2)*6e4;
// Adjust time value by offset, create a Date and return it
// Subtraction also converts the time value to a number
return new Date(b[0] - offset);
}
var s = '/Date(862588800000+0800)/';
console.log(parseDate(s));
The validation could also use a regular expression like:
/\(-?\d+[+-]\d{4}\)/.test(s)
As for formatting the Date, there are many questions about that already, see Where can I find documentation on formatting a date in JavaScript?
Upvotes: 2