javascript - How can I split a string given a specific format? -


i have dates in string format this: 05-11-2009 16:59:20 , sometime this: 2013-12-05t22:00:00:00z , other time this: 2013-12-05t22:00:00:00.000z.

i wrote function extract month day , year dates, function can work of them passing in input format. like:

function dateparts(datetime, format) {     var matches = datetime.splitbyformat(format);      this.getyear = function () {        return matches[3];     };     this.getmonth = function () {         return (matches[2] - 1) +"" ;     };     this.getday = function () {         return matches[1];     };     this.gethours = function () {         return matches[4];     };     this.getminutes = function () {     return matches[5];     };     this.getseconds = function () {         return matches[6];     }; }; 

where format soething "yyyy-mm-dd hh:mm:ss" or "dd-mm-yyyythh:mm:ss.dddz" or whatever.

is there nice way of creating splitbyformat function without having substring head off?

this simple class formatanalyzer beginning. works.

formatanalyzer f = new formatanalyzer("yyyy-mm-dd hh:mm:ss"); f.getyear("2013-07-11 15:39:00"); f.getmonth("2013-07-11 15:39:00"); 

where

public class formatanalyzer {      private string format;     private int yearbegin;     private int yearend;     private int monthbegin;     private int monthend;     // ...      public formatanalyzer(string format) {         this.format = format;         analyzeformat();     }      public string getyear(string date) {         return date.substring(yearbegin, yearend);     }      public string getmonth(string date) {         return date.substring(monthbegin, monthend);     }      private void analyzeformat() {         yearbegin = yearend = format.indexof("y");         while (format.indexof("y", ++yearend) != -1) {         }         monthbegin = monthend = format.indexof("m");         while (format.indexof("m", ++monthend) != -1) {         }         // , on year, day, ...     } } 

Comments