Edu*_*yan 15 javascript momentjs
假设我有一个现有的时刻对象:
var m = moment(); // this will default to now
Run Code Online (Sandbox Code Playgroud)
并希望使用新的Date对象更新它,但不要替换整个对象.对我来说,这不是一个可接受的解决方案:
m = moment(new Date());
Run Code Online (Sandbox Code Playgroud)
我可以在docs中找到的唯一解决方案是使用set方法:
m.set({'year': 2013, 'month': 3});
Run Code Online (Sandbox Code Playgroud)
但是通过这种方式,我们需要将现有的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);
Run Code Online (Sandbox Code Playgroud)
但这看起来很丑陋.也许有人可以提出更好的解决方案?
小智 23
它可能有点晚,但您可以将新日期转换为对象(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());
Run Code Online (Sandbox Code Playgroud)
moment("01/01/2000", "DD/MM/YYYY")moment("01 Jan 2000")对于OP,给定一个以特定方式格式化的字符串,您只需将字符串及其格式传递给moment,例如:
moment("01-01-2000 23:45", "DD-MM-YYYY HH:MM")
遮罩有很多选项,这些都在 momentjs 文档中列出。您甚至可以传递一系列可能的掩码,moment 将尝试所有这些掩码,看看它是否可以理解您的原始字符串。