18-moment.js的快速学习与使用

一、格式介绍

1.1.Year, month, and day tokens
Input Example Description
YYYY 2014 4 or 2 digit year
YY 14 2 digit year
Q 1..4 Quarter of year. Sets month to first month in quarter.
M MM 1..12 Month number
MMM MMMM Jan..December Month name in locale set by moment.locale()
D DD 1..31 Day of month
Do 1st..31st Day of month with ordinal
DDD DDDD 1..365 Day of year
X 1410715640.579 Unix timestamp
x 1410715640579 Unix ms timestamp
1.2.Week year, week, and weekday tokens
Input Example Description
gggg 2014 Locale 4 digit week year
gg 14 Locale 2 digit week year
w ww 1..53 Locale week of year
e 1..7 Locale day of week
ddd dddd Mon...Sunday Day name in locale set by moment.locale()
GGGG 2014 ISO 4 digit week year
GG 14 ISO 2 digit week year
W WW 1..53 ISO week of year
E 1..7 ISO day of week
1.3.Hour, minute, second, millisecond, and offset tokens
Input Example Description
H HH 0..23 24 hour time
h hh 1..12 12 hour time used with a A.
a A am pm Post or ante meridiem
m mm 0..59 Minutes
s ss 0..59 Seconds
S 0..9 Tenths of a second
SS 0..99 Hundreds of a second
SSS 0..999 Thousandths of a second
SSSS 0000..9999 fractional seconds
Z ZZ +12:00 Offset from UTC as +-HH:mm, +-HHmm, or Z

二、基本使用

2.1.安装:
  • 方法一:nodejs中:npm install moment
    var moment = require("moment");

  • 方法二:

<script src="moment.js"></script>
<script>
    moment().format();
</script>
2.2.使用:
  • 获取当前时间:
var now1 = moment();
console.log(now1);      //moment("2018-02-27T15:36:48.299")

var now2 = moment(new Date());
console.log(now2);      //moment("2018-02-27T15:36:48.318")
  • 获取日期和星期:
var day = (new Date()).getDay();
console.log(day);         //星期:2
var date = (new Date()).getDate();
console.log(date);         //日期:27
  • 时间戳:
//Unix偏移量(毫秒),参考时间点:1970
var day1 = moment(1318781876406);
console.log(day1);          //moment("2011-10-17T00:17:56.406")

//Unix时间戳(秒)
var day2 = moment.unix(1318781876);
console.log(day2);          //moment("2011-10-17T00:17:56.000")
var day3 = moment.unix(1318781876.406);
console.log(day3);          //moment("2011-10-17T00:17:56.406")
  • 通过数组来设置时间:
//moment(数组) 和 new Date()的月份是从 0 开始计算的
//Note that like moment(Array) and new Date(year, month, date), months are 0 indexed.
var day4 = moment([2018,5,10]);
console.log(day4);          //moment("2018-06-10T00:00:00.000")
  • 日期克隆的两种方式
//方式一:moment(Monent);
var momentClone11 = moment([2018]);
var momentClone12 = moment(momentClone11);
momentClone11.year(2016);
console.log(momentClone11.year());  //2016
console.log(momentClone12.year());  //2018
//方式二:通过 clone 方法;
var momentClone21 = moment([2014]);
var momentClone22 = momentClone21.clone();
momentClone21.year(2012);
console.log(momentClone21.year());  //2012
console.log(momentClone22.year());  //2014
  • UTC
//UTC :By default, moment parses and displays in local time.
//If you want to parse or display a moment in UTC, you can use moment.utc() instead of moment()
var utc = moment.utc(1318781876406);
var noUtc = moment(1318781876406);
console.log(utc);       //moment.utc("2011-10-16T16:17:56.406+00:00")
console.log(noUtc);     //moment("2011-10-17T00:17:56.406")

var a = moment();
var b = moment.utc();
console.log(a);                 //moment("2018-02-28T11:11:18.375")
console.log(b);                 //moment.utc("2018-02-28T03:11:18.375+00:00")
console.log(a.format());        //2018-02-28T11:11:18+08:00
console.log(b.format());        //2018-02-28T03:11:18Z
console.log(a.valueOf());       //1519787478375
console.log(b.valueOf());       //1519787478375

//UTC 和 本地时间切换
var utcLocal = moment.utc([2018,2,28,10]);
console.log(utcLocal.hours());      //10
utcLocal.local();
console.log(utcLocal.hours());      //18
utcLocal.utc();
console.log(utcLocal.hours());      //10
  • 时区:
//var zone1 = moment.parseZone("2013-01-01T00:00:00-13:00").zone(); // 780
//Deprecation warning: moment().zone is deprecated, use moment().utcOffset instead.
//for example:
//moment().zone()  360  is replaced by moment().utcOffset()  -360
var z = "2013-01-01T00:00:00-13:00";
var zone1 = moment.parseZone(z).utcOffset();
console.log(zone1);     //-780

var zone2 = moment(z).utcOffset(z);     //moment#zone 已经被废弃,取而代之的是
console.log(zone2);
  • 合法性校验:
//合法性校验 Moment applies stricter initialization rules than the Date constructor.
var date1 = new Date(2014,13,32);
console.log(date1.toString());      //Wed Mar 04 2015 00:00:00 GMT+0800 (中国标准时间)
var date2 = moment([2013,13,32]);
console.log(date2.format());     //Invalid date
console.log(date2.isValid());   //false
//不合法的日期包括:
//overflow:比如13个月、一个月32天、一年367天等等;可通过 invalidAt 获取具体报错位置(0:years;1:months;2:days;3:hours;4:minutes;5:seconds;6:milliseconds,-1:means no overflow)
var date3 = moment("2017-03-05 23:17:60.99");
console.log(date3.invalidAt());     //5     如果有多个错,会返回第一个错误的位置

//empty     moment("")
//nullInput     moment(null)
//invalidFormat     moment("2016-08-31",[])
  • 默认值:
//如果没有指定任何值,则 moment() 获取到的值为当前时间
//如果指定日期,则获取到当前的年月;
//如果指定月份,则获取到当前年,日期为01;
//如果指定年份,则获取到的月份和日期都为01
//其中时间如果没有指定:0 for hours, minutes, seconds and milliseconds.
var def01 = moment("10","MM");
console.log(def01.format());    //2018-10-01T00:00:00+08:00
  • 赋值和取值:


    日历表
//毫秒
var sg = moment("2018-02-28 18:20:30.600");
console.log(sg);    //moment("2018-02-28T18:20:30.600")
console.log(sg.millisecond());  //600
sg.millisecond(800);
console.log(sg.millisecond());  //800
console.log(sg.milliseconds());  //800

//秒second(s)、分minute(s)、时hour(s)、日期date(s)
console.log(sg);    //moment("2018-02-28T18:20:30.800")
console.log(sg.second());   //30
console.log(sg.seconds());  //30

//星期
console.log(sg.day());  //3,     2018-02-28 是星期三
sg.day(2)
console.log(sg.format());   //2018-02-27T18:20:30+08:00
sg.day(-3);                 //上周日为0,-3为上周日的日期,继续往前推三天
console.log(sg.format());   //2018-02-22T18:20:30+08:00

console.log(sg.day("Monday"));  //moment("2018-02-19T18:20:30.800"),获取的日期为sg日期所在周的星期一的日期

//星期(区域标准)[有些地方每周第一天是星期日,有些是星期一,中国每周的第一天为星期日]
console.log(moment().weekday());    //3
var week = moment().weekday(1);
console.log(week);      //moment("2018-02-25T16:06:56.635")

//星期(ISO)[这里规定 1 为星期一,7 为星期日]
console.log(moment().isoWeekday(1));    //moment("2018-02-26T16:15:35.969")
console.log(moment().isoWeekday(0));    //moment("2018-02-25T16:15:35.969")
console.log(moment().isoWeekday(7));    //moment("2018-03-04T16:15:35.970")

//天
console.log(moment().dayOfYear());  //59
console.log(moment().dayOfYear(60));    //moment("2018-03-01T16:18:31.392")

//周week(s)[获取这是一年的第几周]
console.log(moment().week());   //9,2月28所在的周确实是第9周
console.log(moment().week(8));  //moment("2018-02-21T16:27:18.511")。解析:如果今天是第九周的星期三,“moment().week(8)”获取到的为第八周的星期三的日期

//月month(s)[取值范围:0-11]
console.log(moment().month());  //1

console.log(moment().month(2)); //moment("2018-03-28T16:51:46.827")。解析:当前日期是2月28日,“moment().month(2)”为3月28日

console.log(moment().month("May")); //moment("2018-05-28T16:57:18.295")

//2.1.0版本之前和之后获取的值不一样
// 2.1.0版本之前:if a moment changed months and the new month did not have enough days to keep the current day of month, it would overflow to the next month[意思是如果超出,会累加到下个月]
// 2.1.0版本之后:this was changed to be clamped to the end of the target month[显示到目标月的最后一天,不会累加到下月]
console.log(moment("2018-01-31").month(1).format("YYYY-MMM-DD"));   //2018-Feb-28
console.log(moment("2018-01-30").month(1).format("YYYY-MMM-DD"));   //2018-Feb-28
console.log(moment("2018-01-29").month(1).format("YYYY-MMM-DD"));   //2018-Feb-28
console.log(moment("2018-01-28").month(1).format("YYYY-MMM-DD"));   //2018-Feb-28
console.log(moment("2018-01-27").month(1).format("YYYY-MMM-DD"));   //2018-Feb-27

//周数
console.log(moment().weeksInYear());    //52
console.log(moment().week());           //9
console.log(moment().isoWeeksInYear()); //52

//取值:
//moment().get("year") === moment().year()
//其它可赋值的有:year、month[0 to 11]、date、hour、minute、second、millisecond

//赋值:
// moment().set(String,Int); ==> moment().set('year', 2013);
//moment().set(Object(String, Int)); ==> moment().set({'year': 2013, 'month': 3});
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,716评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,558评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,431评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,127评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,511评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,692评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,915评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,664评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,412评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,616评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,105评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,424评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,098评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,096评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,869评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,748评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,641评论 2 271

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,106评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 8,592评论 0 23
  • 最近项目中用到自定义日历组件,找来找去,最后发现GitHub的material-calendarview这个项目最...
    colin2017阅读 1,442评论 0 0
  • 沥人土土阅读 235评论 0 1
  • 城市,灯光闪烁明明暗暗如人们殷勤的眼眸在那挺拔的的高楼里晃着在穿梭的车子旁伫立着 排着一条长龙前面看不见蠕动的趋势...
    湖雨阅读 197评论 2 17