關於時間的處理

 js獲取當前時間

var myDate = new Date();  //獲取系統當前時間:Tue Aug 14 2018 15:10:17 GMT+0800 (中國標準時間)javascript

  • myDate.getYear();  //獲取當前年份(2位),如今貌似沒有這個方法了
  • myDate.geyFullYear();  //獲取當前年份(4位):18
  • myDate.getMonth();  //獲取當前月份(0-11,0表明1月):7
  • myDate.getDate();  //獲取當前日(1-31):14
  • myDate.getDay();  //獲取當前星期X(0-6,0表明星期天):2
  • myDate.getTime();  //獲取當前時間(從1970.1.1開始的毫秒數):1534230986220
  • myDate.getHours();  //獲取當前小時數(0-23):15
  • myDate.getMinutes();  //獲取當前分鐘數(0-59):16
  • myDate.getSeconds();  //獲取當前秒數(0-59):36
  • myDate.getMilliseconds();  //獲取當前毫秒數(0-999):220
  • myDate.toLocaleDateString();  //獲取當前日期:2018/8/14
  • myDate.toLocaleTimeString();  //獲取當前時間:下午2:51:21
  • myDate.toLocaleString();  //獲取日期與時間:2018/8/14 下午2:51:21

在調用上述方法時還發現了一系列getUTCHours()的方法,好奇的小手點了百度查了一下UTC:java

不屬於任意時區。協調世界時,又稱世界統一時間,世界標準時間,國際協調時間,簡稱UTC。spa

例如:code

getHours()是獲取本時區的時間,getUTCHours()是獲取UTC時間,咱們是位於東八區,UTC時間是咱們的時區時間減8小時,若是咱們如今是上午11點,UTC時間就是上午3點。orm

 js獲取當前時間戳

時間戳(timestamp),一個能表示一份數據在某個特定時間以前已經存在的、 完整的、 可驗證的數據,一般是一個字符序列,惟一地標識某一刻的時間。ip

!能夠直接比較時間戳的大小來判斷時間的前後字符串

獲取方法

  • var timestamp = Date.parse(new Date())

這裏獲得的結果將後三位(毫秒)轉換成了000顯示,使用時可能會出現問題。例如動態添加頁面元素id的時候,不建議使用。get

  • var timestamp = (new Date()).valueOf()
  • var timestamp = new Date().getTime()

時間戳轉換爲日期格式

function timestampToDate(timestamp, format){
    var time
    //時間戳爲10位需*1000,時間戳爲13位的話不需乘1000
    if((timestamp+"").length == 10){
        time = timestamp * 1000
    }else{
        time = timestamp
    }
    var date = new Date(time);    
    var map = {
        "M": date.getMonth() + 1, //月份
        "d": date.getDate(), //日
        "h": date.getHours(), //小時
        "m": date.getMinutes(), //分
        "s": date.getSeconds(), //秒
        "q": Math.floor((date.getMonth() + 3) / 3), //季度
        "S": date.getMilliseconds() //毫秒
    };
    format = format.replace(/(y+|M+|d+|h+|m+|s+|q+|S+)/g, function (all, t) {
        t = t.charAt(0);
        var v = map[t];
        if (v !== undefined) {
            if (all.length > 1) {
                v = '0' + v;
                v = v.substr(v.length - 2);
            }
            return v;
        }else if (t === 'y') {
            return (date.getFullYear() + '').substr(4 - all.length);
        }
        return all;
    });
    return format;
}
//console.log(formatDate('1403058804342', 'yyyy-MM-dd hh:mm:ss')),獲得:2014-06-18 10:33:24

 * js獲取number的length?io

一、調用toString方法轉爲字符串後取長度console

var num = 123456;

alert(num.toString().length);

二、隱式轉字符串後取長度

var num = 123;
alert((num + '').length)

日期格式轉換爲時間戳

var date = new Date('2014-04-23 18:55:49:123');
// 有三種方式獲取
var time1 = date.getTime();
var time2 = date.valueOf();
var time3 = Date.parse(date);
console.log(time1);//1398250549123
console.log(time2);//1398250549123
console.log(time3);//1398250549000
相關文章
相關標籤/搜索