Man*_*sen 0 javascript datetime date
我需要将一个日期字符串转换为实际日期,我可以用来比较哪些日期最早.
我的日期是这种格式"2010年1月2日"我知道我应该使用某种类型的日期格式,但不知道如何使用javascript.
这是我得到的代码:
function checkOutboundAndReturnDates(outboundDate, returnDate) {
var outboundDatetime = new Date(outboundDate);
var returnDatetime = new Date(returnDate);
var date = new Date("2017-03-25");
console.log(outboundDate);
console.log(returnDate);
console.log("Converting dates");
console.log(outboundDatetime);
console.log(returnDatetime);
console.log(date);
// String string = "January 2, 2010";
// DateFormat format = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
// Date date = format.parse(string);
}
Run Code Online (Sandbox Code Playgroud)
var日期正在运行,但这仅用于测试,而不是我想要的.得到了数字的一天,数字中的年份,但文本中的月份,就像我写的:
"January 2, 2010"
Run Code Online (Sandbox Code Playgroud)
更新
var outboundDateTime = moment(outboundDate, "MMMM DD, YYYY");
var returnDateTime = moment(returnDate, "MMMM DD, YYYY");
console.log(outboundDateTime.format("YYYY-MM-DD"));
console.log(returnDateTime.format("YYYY-MM-DD"));
if (outboundDateTime > returnDateTime) {
console.log("its bigger");
return true;
}
else {
return false;
}
Run Code Online (Sandbox Code Playgroud)
在我的js文件之上,我有:
var moment = require('moment');
Run Code Online (Sandbox Code Playgroud)
已经通过npm安装了它.
我会使用moment.js来处理js中的日期.您可以使用以下时间解析日期字符串:
var outboundDateTime = moment(outboundDate, "MMMM DD, YYYY");
Run Code Online (Sandbox Code Playgroud)
并用它格式化
console.log(outboundDateTime.format("YYYY-MM-DD"));
Run Code Online (Sandbox Code Playgroud)
或检查哪一个更早
console.log(outboundDateTime.isBefore(inboundDateTime));
Run Code Online (Sandbox Code Playgroud)
var dateString1 = "January 2, 1999";
var dateString2 = "January 21, 1999";
var format = "MMMM DD, YYYY";
var outboundDateTime = moment(dateString1, format);
var returnDateTime = moment(dateString2, format);
console.log(outboundDateTime.format("YYYY-MM-DD"));
console.log(returnDateTime.format("YYYY-MM-DD"));
if (outboundDateTime.isAfter(returnDateTime)) {
console.log("its bigger");
}
else {
console.log("not");
}Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment-with-locales.min.js"></script>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
72 次 |
| 最近记录: |