Get Date/time from String in Javascript using RegExp

Date manipulation without plugin is a night-mare, but some places we don’t need to add more dependency over a minor tasks, When i came across time zone date conversion which has more dependency in the code so decided to use RegExp instead of new Date(string), Here a quick fix to get date strings with less effort and preserve data format that you already have,
Note : Make sure your date string is UTC format, if you have problem with date zone conversion refer my post


function getDateTimeString(flag,rawDate){
    switch(flag){
		case 'date':
			var month = rawDate.match(/\w.[a-z]+/g);
            var date = rawDate.match(/\d.\s+/g);
		return month[1]+" "+date[0];
		break;
		case 'time':
			var timeArray = rawDate.match(/\d+/g)
			if(timeArray[1] <= 12){
				var t = timeArray[1]+":"+timeArray[2]+" AM";
			}else{
				var t = timeArray[1]-12+":"+timeArray[2]+" PM";
			}
			return t;
		break;
	}
}

var dateString = ‘Tue Jan 27 04:30:00 UTC+0530 2015’;

getDateTimeString(‘month’,dateString); Output ==> Jan 27

getDateTimeString(‘time’,dateString); Output ==> 04:30 AM

Give a try jsFiddle

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s