0 Pad Day and Month in a Date String using JavaScript -


using javascript there way take date string 9/17/2014 , modify day , month values padded 0 if single digit in length?

the catch delimiter / can anything. - or / if looked 2 fine to.

also order of day, month, , year can in position.

my end goal take date string , make date portion 10 characters in length can grab remaining characters exist , assume time portion of datetime string.

if string though 9/17/2014 date portion 9 long , if day single digit 9/7/2014 8 long.


i working on javascript function convert date string js date object. allows style delimiter , order day, month, , year parts.

my goal modify allow date strings can have time after date part , parse them time pieces.

if string has time parts, assume time delimiter :.

the separator between date , time in string either:

  1. space 04/04/2016 12:23:12
  2. t 04/04/2016t12:23:12

also time may or may not have ending am or pm.

my issue @ moment date part not being 10 character length if auto 0 pad single digit day , months might in end goal.

any of goal appreciated though, thanks


  // convert date string js date object   // can parse multiple date formats   // stringtodate("17/9/2014", "dd/mm/yyyy", "/");   // stringtodate("9/17/2014", "mm/dd/yyyy", "/");   // stringtodate("9-17-2014", "mm-dd-yyyy", "-");   stringtodate: function(d, _format, _delimiter) {     if((d instanceof date)){       return d;     }     if(d.length > 10){       // might have time string @ end       var datestring = d.substring(0, 10);       console.log(datestring);     }      var formatlowercase = _format.tolowercase();     var formatitems = formatlowercase.split(_delimiter);     var dateitems = d.split(_delimiter);     var monthindex = formatitems.indexof("mm");     var dayindex = formatitems.indexof("dd");     var yearindex = formatitems.indexof("yyyy");     var month = parseint(dateitems[monthindex]);     month -= 1;     var formateddate = new date(dateitems[yearindex], month, dateitems[dayindex]);     return formateddate;   }, 

you can use iterating function pad out date:

function pad(str) {   if (str.length === 2) return str;   return pad('0' + str); } 

and use mediating function separate date components , pad them necessary:

function paddate(str, delimiter) {   return str.split(delimiter).map(function (el) {     if (el.length < 2) return pad(el);     return el;   }).join(delimiter); } 

declare want delimiter parameter paddate function.

paddate('9/17/2014', '/'); // 09/17/2014 paddate('19-7-2014', '-'); // 19-07-2014 

demo


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -