如何设置现有时刻.js对象的日期
How to set Date of an existing moment.js object
假设我有一个现有的时刻对象:
var m = moment(); // this will default to now
并希望使用新的 Date 对象更新它,但不替换整个对象。 例如,这对我来说不是一个可接受的解决方案:
m = moment(new Date());
我能在那里的文档中找到的唯一解决方案是使用 set 方法:
m.set({'year': 2013, 'month': 3});
但通过这种方式,我们需要将现有的 Date 对象拆分为这样的和平:
var myDate = new Date();
var newDate = moment(myDate);
var splittedDate = {
year: newDate.get('year'),
month: newDate.get('month'),
date: newDate.get('date'),
hour: newDate.get('hour'),
minute: newDate.get('minute'),
second: newDate.get('second'),
millisecond: newDate.get('millisecond')
};
m.set(splittedDate);
但这对我来说看起来很丑陋。也许有人可以提出更好的解决方案?
可能有点晚了,但您可以将新日期转换为对象( newDate.toObject()
),并将其传递给上一个时刻对象的set
方法:
var m = moment(); // Initial moment object
// Create the new date
var myDate = new Date();
var newDate = moment(myDate);
// Inject it into the initial moment object
m.set(newDate.toObject());
- 例:1
moment("01/01/2000", "DD/MM/YYYY")
- 例:2
moment("01 Jan 2000")
对于 OP,给定以特定方式格式化的字符串,您只需将字符串及其格式传递给 moment,例如:
moment("01-01-2000 23:45", "DD-MM-YYYY HH:MM")
掩码有很多选项,这些都列在momentjs文档中。您甚至可以传递一系列可能的掩码,moment 会尝试所有掩码,看看它是否可以理解您的原始字符串。
只需使用您的Date
对象作为参数:
var d = new Date();
var m = moment(d);
瞧,您的时刻对象设置为与日期对象相同的时间。
相关文章:
- 使用时刻.js从日期时间中提取时间
- 时刻时区.js允许我传递时区缩写并获取转换后的日期/时间
- 时刻.js时区值返回错误的时间戳
- 如何设置现有时刻.js对象的日期
- 时刻.js 24小时制,处理第24小时
- 时刻.js + 实时戳时间前基于 UTC 来自服务器的日期时间
- 相同的日期,但不同的日子与时刻js
- 用户输入时刻js的两个日期之间的差异
- AngularJs 和时刻.js不起作用
- 时刻.js以日期中间格式包含文本
- 时刻.js转换 MM/dd/yyyy 格式日期
- 如何在 Karma 中配置 System.js 以测试取决于时刻.js的代码
- 获取时刻.js unix 时间戳中的时刻 0
- 时刻.js在特定时间创建弹出窗口
- 使用时刻.js获取不同时区的当前时间
- 使用时刻修改日期.js
- 时刻.js - 更改已格式化的过去日期的格式
- 使用时刻验证日期时出现问题.js按格式
- 从时刻 js 对象中提取时间
- 向上舍入/向下舍入一个时刻js 时刻到最接近的分钟