简体   繁体   中英

Using regular expressions, how do I convert a date time string to a short date format?

I am using AngularJS and we have a directive that uses a stored Regex to convert a bound value. So if I create this tag: <span ng-pattern="regex.Zip"></span> then Angular will reference the stored Regex and convert on the fly. I need a regex to format a date.

Example string:

2014-01-01T00:00:00.0000000

Desired output:

01/01/2014

BONUS desired output (if possible with regex alone)!:

01/01/2014 12:00am

This needs to be done with Javascript.

Using a regex :

var longdate = '2014-01-01T00:00:00.0000000';
var shortdate = longdate.replace(
    /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}).(\d{7})$/,
    '$3/$2/$1'
);
console.log(shortdate); // 01/01/2014

Using the Date object :

This allow you to get the hour under 12h format.

var longdate = '2014-01-01T00:00:00.0000000';

var date = new Date(longdate);

var day = ('0' + date.getDate()).slice(-2);        // add a leading 0
var mon = ('0' + date.getMonth()+1).slice(-2);     // month go from 0 to 11
var yea = date.getFullYear();
var hou = ('0' + date.getUTCHours()%12).slice(-2); // back to 0 when we reach 12
var min = ('0' + date.getMinutes()).slice(-2);
var suf = date.getUTCHours() >= 12 ? 'pm' : 'am';
var shortdate = day+'/'+mon+'/'+yea+' '+hou+':'+min+suf;

console.log(shortdate); // 01/00/2014 00:00am 

javascript code without regex

var d = new Date('2014-01-01T00:00:00.0000000'); 
var date = d.toLocaleDateString();  // 01/01/2014

Here's a solution with python.

from datetime import datetime

raw = '2014-01-01T00:00:00.0000000'
dt = datetime.strptime(raw, '%Y-%m-%dT%H:%M:%S.%f0') 
print dt.strftime('%d/%m/%Y %H:%M%p')

I'm taking the string, changing it to a datetime object, then formatting it. It's very easy to get your head around it, check it out more here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM