js获取当前时间;时间戳转换;前n小时的时间;前n分钟的时候

最终转换的时间格式都是 yyyy-mm-dd hh-mm-ss

//时间位数为1位数时,前面补0
var setFormat=function (x) {
  if (x < 10) {
    x = "0" + x;
  }
  return x;
 }


//时间戳转换(Y+M+D+h+m+s)
function transtimestamp (timestamp){
if(timestamp==null||timestamp==''){
return ''; 
}
var date = new Date(timestamp);
Y = date.getFullYear() + '-';
M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
D = setFormat(date.getDate()) + ' ';
h = setFormat(date.getHours()) + ':';
m = setFormat(date.getMinutes()) + ':';
s = setFormat(date.getSeconds()); 
return(Y+M+D+h+m+s); 
}


//获取当前时间

function getNowtime(){
var date = new Date(); //日期对象
var now = "";
now = date.getFullYear()+"-"; //读英文就行了
now = now + (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';//取月的时候取的是当前月-1如果想取当前月+1就可以了
now = now + setFormat(date.getDate())+" ";
now = now + setFormat(date.getHours())+":";
now = now + setFormat(date.getMinutes())+":";
now = now + setFormat(date.getSeconds())+"";
return now;

}



//获取从现在到 beforetime 小时前的时间(beforetime 只能是整数)
function beforeNowtime(beforetime){
    var date = new Date(); //日期对象
    date.setHours (date.getHours () - beforetime);
    var now = "";
    now = date.getFullYear()+"-"; //读英文就行了
    now = now + (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';//取月的时候取的是当前月-1如果想取当前月+1就可以了
    now = now + setFormat(date.getDate())+" ";
    now = now + setFormat(date.getHours())+":";
    now = now + setFormat(date.getMinutes())+":";
    now = now + setFormat(date.getSeconds())+"";
    return now;
}

//获取从现在到 beforetime 分钟前的时间
function beforeNowtimeByMinu(beforetime){
    var date = new Date(); //日期对象
    date.setMinutes (date.getMinutes () - beforetime);
    var now = "";
    now = date.getFullYear()+"-"; //读英文就行了
    now = now + (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';//取月的时候取的是当前月-1如果想取当前月+1就可以了
    now = now + setFormat(date.getDate())+" ";
    now = now + setFormat(date.getHours())+":";
    now = now + setFormat(date.getMinutes())+":";
    now = now + setFormat(date.getSeconds())+"";
    return now;
}


实现原理:js对于时间戳的操作,可以查询w3school:

http://www.w3school.com.cn/jsref/jsref_obj_date.asp

你可能感兴趣的:(JS)