简体   繁体   中英

JavaScript Regex Convert long date time to short date and covert long number to 2 decimal places

hi everyone I have a simple javascript problem and am hoping someone could help me with this

function changeDate(){
var date = '2/1/2013 12:00:00 AM';

var newDate = date.replace^(?ni:(?=\d)((?'year'((1[6-9])|([2-9]\d))\d\d)(?'sep'[/.-])(?'month'0?[1-9]|1[012])\2(?'day'((?<!(\2((0?[2469])|11)\2))31)|(?<!\2(0?2)\2)(29|30)|((?<=((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(16|[2468][048]|[3579][26])00)\2\3\2)29)|((0?[1-9])|(1\d)|(2[0-8])))(?:(?=\x20\d)\x20|$))?((?<time>((0?[1-9]|1[012])(:[0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2}))?)$

alert(newDate); // i need this to alert just '02/01/2013'

}


 function twoDecimalPlace{

var decimal = '1904686.92000000';
//do something;

alert(decimal) // this should alert 1904686.92
 }

So basically I need to truncate time and get short date. And for the decimal place i need it to be shortened to 2 decimal places and also see if it is like 0.988 then that should be 0.99 round off to the next largest if trailing number is greater than 5

A regular expression is not the right tool for the job.

You should use Date() then use methods like getDate() , getFullYear() , etc to reformat the date.

As for decimal places:

var x = twoDecimalPlace('1904686.92600000');
alert(x);
function twoDecimalPlace(decimal){
    var result = Number(decimal).toFixed(2);
    return(result);
 }

http://jsfiddle.net/6etNB/

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