My java script application uses .net web service to get the data from back end. Everything works fine except for date / time conversion. I need to convert the epoch date returned by service to user's local browser date.
The web service returns date in the below format,
/Date(1335341422660-0500)/
This is what I have done to convert this to human readable date,
I strip out everything after hyphen (-) and use the remaining data for date conversion
var dateVal=dateField.replace(/-.*\)/g,')');
var date = new Date(parseFloat(dateVal.substr(6)));
var dateArray=date.toString().split(" ");
if(dateArray.length>3){
timeZone=("("+dateArray[4])+")"
}
var month=date.getMonth() + 1;
var year=date.getFullYear();
var date=date.getDate();
var hours= date.getHours();
var offset=date.getTimezoneOffset();
var finalDateStr=(year+"-"+month+"-"+dateValue)+" "+hours+":"+
minutes+":"+seconds+" "+timeZone;
For the above epoch value, expected date is,
4/24/2012 9:10:22 PM - This date is displayed in a .net application which is actually the source application that inserts this date in to MS SQL server whenever a new item is created / updated. They convert the SQL server date to local date (using .net) and display it in UI.
but when I form the date using the above script I am getting the value as,
2012-4-25 4:10:22 (EDT) (7 hours more compared to above date).
I am not sure where I am wrong.. Can some one help me figure out this issue?
对于此类日期操作,您可能需要考虑使用Moment.js 。
Not sure if this is a great way to fix this issue...
This is what I did and seems to work fine... Again I dont think this is a fool proof solution but I checked in various time zones (with / without daylight saving time) and it seems to work......
var dateVal=dateField.replace(/-.*\)/g,')');
var date = new Date(parseFloat(dateVal.substr(6)));
var dateArray=date.toString().split(" ");
var timeZone="(Local Time)";
if(dateArray.length>3){
timeZone=("("+dateArray[4])+")"
}
var date2=dateField.split("-");
var dateOffset=(date2[1].toString().replace(")","").replace("/",""));
if( date.toString().toUpperCase().indexOf("DT")!==-1){
date.setHours(date.getHours()-(parseFloat(parseFloat(dateOffset).toString().replace(/0*$/, ''))+2));
}else{
date.setHours(date.getHours()-(parseFloat(parseFloat(dateOffset).toString().replace(/0*$/, ''))+1));
}
var month=date.getMonth() + 1;
var year=date.getFullYear();
var dateValue=date.getDate();
var hours= date.getHours();
var minutes= date.getMinutes();
var seconds=date.getSeconds()
var finalDateStr=(year+"-"+month+"-"+dateValue)+" "+hours+":"+
minutes+":"+seconds+" "+timeZone;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.