Thứ Tư, 27 tháng 2, 2013

Javascript: Convert Datetime

- Convert Date time by Timezone: (Example convert date time to New Zealand time zone)

/// <summary>
/// Convert local date time to New Zealand timezon
/// </summary>
/// <param name="dateTime" type="DateTime">local datetime</param>
ConvertByNZTimeZone: function (dateTime) {
 //daylight saving
 var dateStartCurrentYear = new Date(dateTime.getFullYear(), 8, 30, 2, 0, 0, 0),
  dateEndNextYear = new Date(dateTime.getFullYear() + 1, 3, 7, 3, 0, 0, 0),
        dateStartPrevYear = new Date(dateTime.getFullYear() - 1, 8, 30, 2, 0, 0, 0),
  dateEndCurrentYear = new Date(dateTime.getFullYear(), 3, 7, 3, 0, 0, 0),
  offset = 12; //offset timezone
            
    //detect base on:
 //   - start date from previous year and end date of current year
 //   - start date from current year and end date of next year
 if ((dateStartPrevYear <= dateTime && dateTime <= dateEndCurrentYear) ||
        (dateStartCurrentYear <= dateTime && dateTime <= dateEndNextYear)) {
  offset = 13;
 }
 
 // convert to msec
 // add local time zone offset 
 // get UTC time in msec
 utc = dateTime.getTime() + (dateTime.getTimezoneOffset() * 60000);
 
 // create new Date object for different city
 // using supplied offset
 nd = new Date(utc + (3600000 * offset));
 
 // return time as a string
 return nd;
}


- Convert UTC date string to local date time:
// <summary>
// Convert json utc date string to local date.
// </summary>
// <param name=utcString>Utc string</param>
function ConvertUTCDate(uctString) {
 if (!uctString) {
  return null;
 }
 
 if ($.browser.mozilla && uctString.indexOf("Z") === -1) {
  uctString += "Z";
 }
 
 var date = new Date(uctString);
 
 return date; 
}


Không có nhận xét nào:

Đăng nhận xét