将日期从DD-MM-YYYY转换为DD / MM / YYYY,并找到差异 [英] Converting a date from DD-MM-YYYY to DD/MM/YYYY in Javascript and finding the difference
问题描述
我正在尝试将DD-MM-YYYY中的日期(从datepicker字段获取)转换为DD / MM / YYYY,并获得两者之间的差异(以年为单位)。
I am trying to convert a date (obtained from a datepicker field) in DD-MM-YYYY to DD/MM/YYYY and get the difference (in years) between the two..
我已经尝试了这个目的:
I have tried this so far:
function calcAge()
{
var now = new Date();
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = (day)+"/" + (month) + "/" + now.getFullYear() ;
var ageday = document.getElementById("datepicker").value.substring(0,2);
var agemonth = document.getElementById("datepicker").value.substring(3,5);
var ageyear = document.getElementById("datepicker").value.substring(6,10);
var tempbday= ageday +"/"+ agemonth +"/"+ ageyear;
var bday = new Date(tempbday);
var diff = Math.round(days_between(bday,today)/365);
//alert(diff);
//document.getElementById("age").value=diff;
}
function days_between(date1, date2)
{
// The number of milliseconds in one day
var ONE_DAY = 1000 * 60 * 60 * 24;
// Convert both dates to milliseconds
var date1_ms = date1.getTime();
var date2_ms = date2.getTime();
// Calculate the difference in milliseconds
var difference_ms = Math.abs(date1_ms - date2_ms);
// Convert back to days and return
return Math.round(difference_ms/ONE_DAY);
}
推荐答案
我正在尝试将DD-MM-YYYY中的日期(从datepicker字段获取)转换为DD / MM / YYYY
I am trying to convert a date (obtained from a datepicker field) in DD-MM-YYYY to DD/MM/YYYY
可以使用简单的替换来完成:
That can be done using a simple replace:
'21-04-2014'.replace(/-/g,'/'); // 21/04/2014
并获得差异)之间的两个
and get the difference (in years) between the two
你想怎么做?年可以有365天或366天,应该使用?你想要十进制年份,年数,日期,年份,月份和日期的答案?
How do you want to do that? Years can have 365 or 366 days, which should be used? Do you want the answer in decimal years, or years and days, or years, months and days?
以下函数将计算整个日期之间的两个日期之间的差异。如果您使用精确的参数,它将不会在几天之内,并将差距缩小到毫秒。请注意,它希望被赋予Date对象,而不是字符串。
The following function will calculate the difference between two dates in whole days. If you use the precise parameter, it will not round the days and will give the difference down to the millisecond. Note that it expects to be given Date objects, not strings.
请参阅下面的代码片段。
See snippet below.
要转换格式为dd-mm-yyyy或dd / mm / yyyy的字符串,您可以使用:
To convert a string in the format dd-mm-yyyy or dd/mm/yyyy you can use:
function parseDMY(s) {
var b = s.split(/\D+/);
return new Date(b[2], --b[1], b[0]);
}
<
To get the difference between say 1 January, 2012 and 22 July, 2014:
console.log(dateDifference(parseDMY('1-1-2012'), parseDMY('22-7-2014')));
// [2, 6, 21, 0, 0, "0.000"] or 2 years, 6 months, 21 days
2012年2月29日至2014年3月1日(闰年可能很棘手):
And between 29 February, 2012 and 1 March, 2014 (leap years can be tricky):
console.log(dateDifference(parseDMY('29-2-2012'), parseDMY('1-3-2014')));
// [2, 0, 1, 0, 0, "0.000"] or 2 years, 0 months, 1 day
2014年1月31日至3月1日(31到30个月可能很棘手,只需增加一个月至2014年1月31日为2014年3月3日):
And between 31 January and 1 March 2014 (31 to 30 day months can be tricky too, simply adding one month to 31 Jan 2014 gives 3 March 2014):
console.log(dateDifference(parseDMY('31-1-2014'), parseDMY('1-3-2014')));
// [0, 1, 1, 0, 0, "0.000"] or 0 years, 1 month, 1 day
// Given two date object, return the difference in years, months and days
// Expects start date to be before end date
// Default is to deal in whole days. For precise differences
// (hours, minutes and seconds), set precise to true
function dateDifference(start, end, precise) {
var timeDiff, years, months, days, hours, minutes, seconds;
// Copy date objects so don't modify originals
var s = new Date(+start);
var e = new Date(+end);
// If not precise, set h,m,s to zero
if (!precise) {
s.setHours(0,0,0,0);
e.setHours(0,0,0,0);
}
// Get estimate of year difference
years = e.getFullYear() - s.getFullYear();
// Add difference to start, if greater than end, remove one year
// Note start from restored start date as adding and subtracting years
// may not be symetric
s.setFullYear(s.getFullYear() + years);
if (s > e) {
--years;
s = new Date(+start);
s.setFullYear(s.getFullYear() + years);
}
// Allow for leap year: 29-Feb + 1 year -> 1-Mar
if (start.getDate() != s.getDate()) {
s.setDate(0);
}
// Get estimate of months
months = e.getMonth() - s.getMonth();
months += months < 0? 12 : 0;
// Add difference to start, adjust if greater
s.setMonth(s.getMonth() + months);
if (s > e) {
--months;
s = new Date(+start);
s.setFullYear(s.getFullYear() + years);
s.setMonth(s.getMonth() + months);
}
// Allow for 31 day month rolling over to 1st
if (start.getDate() != s.getDate()) {
s.setDate(0);
}
// Get remaining time difference
timeDiff = e - s;
days = timeDiff / 8.64e7 | 0;
hours = (timeDiff % 8.64e7) / 3.6e6 | 0;
minutes = (timeDiff % 3.6e6) / 6e4 | 0;
seconds = ((timeDiff % 6e4) / 1e3).toFixed(3);
return [years, months, days, hours, minutes, seconds];
}
// Simple date string parser, doesn't validate values
function parseDMY(s) {
var b = s.split(/\D/)
return new Date(b[2], b[1]-1, b[0]);
}
function calcDiff(el) {
var form = el.form;
var start = parseDMY(form.startDate.value);
var end = parseDMY(form.endDate.value);
if (isNaN(start) || isNaN(end)) return;
var diff = dateDifference(start, end);
document.getElementById('output').innerHTML = diff[0] + ' year' + (diff[0] == 1? ' ' : 's ') +
diff[1] + ' month' + (diff[1] == 1? ' ' : 's ') +
diff[2] + ' day' + (diff[2] == 1? '' : 's');
}
<form id="f">
<table>
<tr><td>Start date (d/m/y)<td><input name="startDate" value="20/03/2016">
<tr><td>End date (d/m/y)<td><input name="endDate" value="20/04/2017">
<tr><td><input type="reset"><td><input type="button" onclick="calcDiff(this)" value="Get difference">
</table>
</form>
<div id="output"></div>
这个闰年还有几个问题,方式...
This still has a few issues for leap years, update on the way…
这篇关于将日期从DD-MM-YYYY转换为DD / MM / YYYY,并找到差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!