我有两个长字符串格式的日期,例如“ 2013年4月11日星期四23:59:59 GMT + 0530(印度标准时间)” 。 / p>
代码:
var x = "Thu Apr 11 2013 23:59:59 GMT+0530 (India Standard Time)"
var today = new Date();
var diff = today.getDate() - x;
alert(diff);
答案 0 :(得分:3)
您可以将日期字符串传入Date()。它将返回日期对象。然后您可以找到差异。
var date1 = new Date("Thu Apr 11 2013 23:59:59 GMT+0530 (India Standard Time)");
var today = new Date();
var diffTime = Math.abs(today .getTime() - date1.getTime());
var diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
console.log(diffDays);
答案 1 :(得分:1)
要查找两个日期之间的差异,应将它们都转换为Date对象。假设您要计算问题中提到的那一天与今天之间的天数之差。
const x = new Date("Thu Apr 11 2013 23:59:59 GMT+0530 (India Standard Time)").setHours(0,0,0,0);
const today = new Date().setHours(0,0,0,0);
const diff = today - x;
const oneDay = 24*60*60*1000;
const result = diff/oneDay;
答案 2 :(得分:1)
JS Date()
类可以将您的字符串解析为一个日期。剩下的只是数学。
var dateFirst = new Date("Thu Apr 11 2013 23:59:59 GMT+0530 (India Standard Time");
var dateSecond = new Date("Thu Apr 12 2013 23:59:59 GMT+0530 (India Standard Time");
// time difference
var timeDiff = Math.abs(dateSecond.getTime() - dateFirst.getTime());
// days difference
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
// difference
console.log(diffDays);
答案 3 :(得分:-1)
您可以使用力矩引用以下示例:
1) Install via NPM dependencies:
npm install moment
2) Import in your Typescript file:
import * as moment from 'moment'
3) Typescript file:
const x = new Date("Thu Apr 11 2013 23:59:59 GMT+0530 (India Standard Time)")
const today = new Date();
let date1 = moment(x, "DD-MM-YYYY");
let date2 = moment(today, "DD-MM-YYYY");
let duration = moment.duration(date1.diff(date2));
let days = duration.asDays();
Moment提供了多种日期差功能。