开发者

converting date-time to rfc3339 format using either jquery or java script

开发者 https://www.devze.com 2023-02-24 08:51 出处:网络
How do I convert the standard date time example: dd/mm/yyyy:12:00 to rfc3339 format example 20100908T070000Z. I need to export the date time details to google calendar,yahoo calendar开发者_C百科,micro

How do I convert the standard date time example: dd/mm/yyyy:12:00 to rfc3339 format example 20100908T070000Z. I need to export the date time details to google calendar,yahoo calendar开发者_C百科,microsoft calendar, ical.


Your requirement seems a bit trivial, is there more to it? Here's the obvious answer:

function formatTimestring(s) {
  var b = s.split(/[\/:]/);
  return b[2] + b[1] + b[0] + 'T' + b[3] + b[4] + '00' + 'Z'
}

alert(
 formatTimestring('08/09/2010:12:00') //20100908T120000Z
);

If you want to generate a UTC string in the requested format from a date object or "now", then:

/*
 *  Return a date string as yyyymmddThhmmssZ
 *  in UTC.
 *  Use supplied date object or, if no
 *  object supplied, return current time 
 */
var dateToUTCString = (function () {

  // Add leading zero to single digit numbers
  function addZ(n) {
    return (n<10)?'0'+n:''+n;
  }

  return function(d) {

    // If d not supplied, use current date
    var d = d || new Date();

    return d.getUTCFullYear() + 
           addZ(d.getUTCMonth() + 1) + 
           addZ(d.getUTCDate()) +
           'T' + 
           addZ(d.getUTCHours()) + 
           addZ(d.getUTCMinutes()) + 
           addZ(d.getUTCSeconds()) +
           'Z';
  }
}());

And if you want to use mm-dd-yyy hh:mm[:ssam/pm]:

// input format: mm-dd-yyy hh:mm:ss[ ]am|pm
function timeStringToUTC(s) {

  // Deal with trailing am/pm if present
  // Probably should trim leading spaces here too
  var isPM = /pm\s*$/i.test(s);
  s = s.replace(/\s*pm\s*$/i,'')

  // Split the string on any of -, space or :
  var b = s.split(/[- :]/);

  // Add 12 to hour if is pm
  if (isPM) {
    b[3] = +b[3] + 12;
  } else {
    // Add leading zero if hours less than 10
    b[3] = (b[3] < 10)? '0' + +b[3] : b[3];
  }

  // Add leading zero to minutes if < 10
  if (b[4] < 10) b[4] = '0' + +b[4];

  // If seconds not supplied, set to 00
  if ( !/^\d\d?$/.test(b[5])) {
    b[5] = '00';
  } else {
    // Add leading zero if seconds less than 10
    if (b[5] < 10) b[5] = '0' + +b[5];
  }

  // Generate date object, call dateToUTCString to return 
  // UTC date string
  return dateToUTCString(
           new Date(b[2] + '/' +
                    b[0] + '/' +
                    b[1] + ' ' +
                    b[3] + ':' +
                    b[4] + ':' +
                    b[5]
               )
         ); 
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号