1. 程式人生 > >關於JavaScript中獲取到的日期的形式

關於JavaScript中獲取到的日期的形式

1 獲取的日期格式及其轉換 (1)var date = new Date()

console.log(date);   //Wed May 03 2017 10:07:16 GMT+0800 (中國標準時間) (2)var date = Date.now()

console.log(date);  //1493777310036 (3)var date = +new Date(); // ie9以下不支援的時候

console.log(date);  //1493777310036

在(1)中,如果date的結果是Wed May 03 2017 10:07:16 GMT+0800 (中國標準時間), console.log(date.toString()); // Wed May 03 2017 10:10:56 GMT+0800 (中國標準時間) console.log(date.toDateString());// Wed May 03 2017 console.log(date.toLocaleDateString()); // 2017/5/3*/

2 注意: var date1 = new Date(2017,04,01) // 表示5月。

var date1 = new Date(‘2017-5-1’) // 等同於上面 console.log(date1) var date2 = new Date(1493777310036) console.log(date2) //Wed May 03 2017 10:08:30 GMT+0800 (中國標準時間) var date3 = new Date() console.log(date3.valueOf()) //1493778043334

這個毫秒數字代表從1970-01-01 至今的毫秒數。 返回時間物件對應的毫秒數字,因此可以直接使用 > < 判斷兩個時期的大小

3 獲取日期中指定部分: getTime() 返回毫秒數和valueOf()結果一樣 getMilliseconds() //毫秒 getSeconds() 返回0-59 getMinutes() 返回0-59 getHours() 返回0-23 getDay() 返回星期幾 0週日 6周6 getDate() 返回當前月的第幾天 getMonth() 返回月份,從0開始 getFullYear() 返回4位的年份 如 2016

4 封裝為2017-05-01 12:12:12 格式

function getDateTime(dt) {

// 先獲取我們需要的所有的元素哦~ var year=dt.getFullYear(); var month=dt.getMonth()+1; var day=dt.getDate(); var h=dt.getHours(); var m=dt.getMinutes(); var s=dt.getSeconds();

// 這裡應該想一下,如果是個數怎麼辦?那就用三元表示式來處理 month=month<10?“0”+month:month; day=day<10?“0”+day:day; h=h<10?“0”+h:h; m=m<10?“0”+m:m; s=s<10?“0”+s:s;

// 下面可以返回了 return year+“年”+month+“月”+day+“日”+h+“時”+m+“分”+s+“秒”; }

// 把這個方法放入我們專案的js檔案中,當我需要的時候直接呼叫就可以了。 getDateTime(new Date());