JavaScript日期对象

91 阅读1分钟

日期对象

  1. new Date()获取的是本地的计算机时间。
  2. 日期对象可以直接相减,得到的是两个时间的相差毫秒数。
var date = new Date();
console.log(date - new Date()); //0
  1. 获取时间
var date = new Date();

var H = date.getHours(),//当前小时
    M = date.getMinutes(),//分钟
    S = date.getSeconds(),//秒
    s = date.getMilliseconds();//毫秒
console.log(H+"小时"+M+"分钟"+ S+"秒" +s+"毫秒");

var year = date.getYear(),//获取到不是年份 获取到的是从1900年到至今的年数
    Year = date.getFullYear(),//年份
    mouth = date.getMonth() + 1,//月份 0~11
    day = date.getDay(),//星期几
    Day = date.getDate(),//天数
    _time = date.getTime();//当前毫秒数 从1970(计算机元年)到当前的毫秒数 (时间戳)

//少用
//toLocaleString 输出本地时间
//toLocaleDateString 本地时间 年月日
//toLocaleTimeString 本地 小时
//UTC  方法可根据世界时返回 1970 年 1 月 1 日 到指定日期的毫秒数

//设置时间
var date1 = new Date(2018,7,24);  //返回指定的时间(注:月份会加一,所以设置的时候要减一)
var date2 = new Date("2018/8/24");  //字符串不需要减一

//已知中国是在东8区 想获取世界时间
console.log(new Date(date.getTime() - 8 * 60 * 60 * 1000).toLocaleString());

//当地时间与世界时间的时差 (分钟) 世界时间 - 当地时间
console.log(date.getTimezoneOffset());