2つの日付の違いを見つける方法は?
8 に答える
Dateオブジェクトとそのミリ秒値を使用して、差を計算できます。
var a = new Date(); // Current date now.
var b = new Date(2010, 0, 1, 0, 0, 0, 0); // Start of 2010.
var d = (b-a); // Difference in milliseconds.
ミリ秒を1000で割って秒に変換し、結果を整数に変換することで、秒数を(整数/整数として)取得できます(これにより、ミリ秒を表す小数部分が削除されます)。
var seconds = parseInt((b-a)/1000);
minutes
次に、60で除算seconds
して整数に変換し、次に60でhours
除算minutes
して整数に変換し、同じ方法でより長い時間単位を使用することで、全体を取得できます。これから、下位単位の値で時間単位の最大全量を取得し、残りの下位単位を取得する関数を作成できます。
function get_whole_values(base_value, time_fractions) {
time_data = [base_value];
for (i = 0; i < time_fractions.length; i++) {
time_data.push(parseInt(time_data[i]/time_fractions[i]));
time_data[i] = time_data[i] % time_fractions[i];
}; return time_data;
};
// Input parameters below: base value of 72000 milliseconds, time fractions are
// 1000 (amount of milliseconds in a second) and 60 (amount of seconds in a minute).
console.log(get_whole_values(72000, [1000, 60]));
// -> [0,12,1] # 0 whole milliseconds, 12 whole seconds, 1 whole minute.
2番目のDateオブジェクトに対して上記で提供された入力パラメーターが何であるか疑問に思っている場合は、以下の名前を参照してください。
new Date(<year>, <month>, <day>, <hours>, <minutes>, <seconds>, <milliseconds>);
このソリューションのコメントに記載されているように、表現したい日付に必要な場合を除いて、必ずしもこれらすべての値を提供する必要はありません。
私はこれを見つけました、そしてそれは私にとってうまくいきます:
2つの既知の日付の差を計算する
残念ながら、2つの既知の日付の間の日、週、月などの日付間隔を計算することは、Dateオブジェクトを一緒に追加することはできないため、それほど簡単ではありません。あらゆる種類の計算でDateオブジェクトを使用するには、最初に、大きな整数として格納されているDateの内部ミリ秒値を取得する必要があります。そのための関数はDate.getTime()です。両方の日付が変換されたら、前の日付から後の日付を引くと、ミリ秒単位の差が返されます。次に、その数値を対応するミリ秒数で割ることにより、目的の間隔を決定できます。たとえば、特定のミリ秒数の日数を取得するには、1日のミリ秒数(1000 x60秒x60分x24時間)である86,400,000で除算します。
Date.daysBetween = function( date1, date2 ) {
//Get 1 day in milliseconds
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 = date2_ms - date1_ms;
// Convert back to days and return
return Math.round(difference_ms/one_day);
}
//Set the two dates
var y2k = new Date(2000, 0, 1);
var Jan1st2010 = new Date(y2k.getFullYear() + 10, y2k.getMonth(), y2k.getDate());
var today= new Date();
//displays 726
console.log( 'Days since '
+ Jan1st2010.toLocaleDateString() + ': '
+ Date.daysBetween(Jan1st2010, today));
部分的な日数が必要かどうかに応じて、丸めはオプションです。
// This is for first date
first = new Date(2010, 03, 08, 15, 30, 10); // Get the first date epoch object
document.write((first.getTime())/1000); // get the actual epoch values
second = new Date(2012, 03, 08, 15, 30, 10); // Get the first date epoch object
document.write((second.getTime())/1000); // get the actual epoch values
diff= second - first ;
one_day_epoch = 24*60*60 ; // calculating one epoch
if ( diff/ one_day_epoch > 365 ) // check , is it exceei
{
alert( 'date is exceeding one year');
}
年、月、日の組み合わせとして表される違いを探している場合は、この関数をお勧めします。
function interval(date1, date2) {
if (date1 > date2) { // swap
var result = interval(date2, date1);
result.years = -result.years;
result.months = -result.months;
result.days = -result.days;
result.hours = -result.hours;
return result;
}
result = {
years: date2.getYear() - date1.getYear(),
months: date2.getMonth() - date1.getMonth(),
days: date2.getDate() - date1.getDate(),
hours: date2.getHours() - date1.getHours()
};
if (result.hours < 0) {
result.days--;
result.hours += 24;
}
if (result.days < 0) {
result.months--;
// days = days left in date1's month,
// plus days that have passed in date2's month
var copy1 = new Date(date1.getTime());
copy1.setDate(32);
result.days = 32-date1.getDate()-copy1.getDate()+date2.getDate();
}
if (result.months < 0) {
result.years--;
result.months+=12;
}
return result;
}
// Be aware that the month argument is zero-based (January = 0)
var date1 = new Date(2015, 4-1, 6);
var date2 = new Date(2015, 5-1, 9);
document.write(JSON.stringify(interval(date1, date2)));
このソリューションは、うるう年(2月29日)と月の長さの違いを、自然に行う方法で処理します(私は思います)。
したがって、たとえば、2015年2月28日から2015年3月28日までの間隔は、28日ではなく、正確に1か月と見なされます。両方の日が2016年である場合でも、差は29日ではなく、正確に1か月になります。
月と日がまったく同じで年が異なる日付は、常に正確な年数の違いがあります。したがって、2015-03-01と2016-03-01の違いは、1年と1日ではなく、正確に1年になります(365日を1年として数えるため)。
この回答は、別の回答(最後のリンク)に基づいており、2つの日付の違いに関するものです。
シンプルであるため、どのように機能するかを確認できます。また、差を
時間の単位(私が作成した関数)に分割し、UTCに変換してタイムゾーンの問題を停止することも含まれます。
function date_units_diff(a, b, unit_amounts) {
var split_to_whole_units = function (milliseconds, unit_amounts) {
// unit_amounts = list/array of amounts of milliseconds in a
// second, seconds in a minute, etc., for example "[1000, 60]".
time_data = [milliseconds];
for (i = 0; i < unit_amounts.length; i++) {
time_data.push(parseInt(time_data[i] / unit_amounts[i]));
time_data[i] = time_data[i] % unit_amounts[i];
}; return time_data.reverse();
}; if (unit_amounts == undefined) {
unit_amounts = [1000, 60, 60, 24];
};
var utc_a = new Date(a.toUTCString());
var utc_b = new Date(b.toUTCString());
var diff = (utc_b - utc_a);
return split_to_whole_units(diff, unit_amounts);
}
// Example of use:
var d = date_units_diff(new Date(2010, 0, 1, 0, 0, 0, 0), new Date()).slice(0,-2);
document.write("In difference: 0 days, 1 hours, 2 minutes.".replace(
/0|1|2/g, function (x) {return String( d[Number(x)] );} ));
上記の私のコードはどのように機能するか
ミリ秒単位の日付/時刻の差は、 Dateオブジェクトを使用して計算できます。
var a = new Date(); // Current date now.
var b = new Date(2010, 0, 1, 0, 0, 0, 0); // Start of 2010.
var utc_a = new Date(a.toUTCString());
var utc_b = new Date(b.toUTCString());
var diff = (utc_b - utc_a); // The difference as milliseconds.
次に、その差の秒数を計算するには、1000で割って
ミリ秒を秒に変換し、結果を整数(整数)に変更し
てミリ秒(その小数の小数部分)を削除しますvar seconds = parseInt(diff/1000)
。
また、同じプロセスを使用して、より長い時間単位を取得できます。たとえば、
-(全体)分、秒を60で除算し、結果を整数に変更します
。-時間、分を60で除算し、結果を整数に変更します。
このデモを使用して、差を
時間の単位全体に分割するプロセスを実行するための関数を作成しました。split_to_whole_units
console.log(split_to_whole_units(72000, [1000, 60]));
// -> [1,12,0] # 1 (whole) minute, 12 seconds, 0 milliseconds.
この答えは、この他の答えに基づいています。
使用することもできます
export function diffDateAndToString(small: Date, big: Date) {
// To calculate the time difference of two dates
const Difference_In_Time = big.getTime() - small.getTime()
// To calculate the no. of days between two dates
const Days = Difference_In_Time / (1000 * 3600 * 24)
const Mins = Difference_In_Time / (60 * 1000)
const Hours = Mins / 60
const diffDate = new Date(Difference_In_Time)
console.log({ date: small, now: big, diffDate, Difference_In_Days: Days, Difference_In_Mins: Mins, Difference_In_Hours: Hours })
var result = ''
if (Mins < 60) {
result = Mins + 'm'
} else if (Hours < 24) result = diffDate.getMinutes() + 'h'
else result = Days + 'd'
return { result, Days, Mins, Hours }
}
結果は{結果: '30d'、日:30、分:43200、時間:720}
Date.prototype.addDays = function(days) {
var dat = new Date(this.valueOf())
dat.setDate(dat.getDate() + days);
return dat;
}
function getDates(startDate, stopDate) {
var dateArray = new Array();
var currentDate = startDate;
while (currentDate <= stopDate) {
dateArray.push(currentDate);
currentDate = currentDate.addDays(1);
}
return dateArray;
}
var dateArray = getDates(new Date(), (new Date().addDays(7)));
for (i = 0; i < dateArray.length; i ++ ) {
// alert (dateArray[i]);
date=('0'+dateArray[i].getDate()).slice(-2);
month=('0' +(dateArray[i].getMonth()+1)).slice(-2);
year=dateArray[i].getFullYear();
alert(date+"-"+month+"-"+year );
}
var DateDiff = function(type, start, end) {
let // or var
years = end.getFullYear() - start.getFullYear(),
monthsStart = start.getMonth(),
monthsEnd = end.getMonth()
;
var returns = -1;
switch(type){
case 'm': case 'mm': case 'month': case 'months':
returns = ( ( ( years * 12 ) - ( 12 - monthsEnd ) ) + ( 12 - monthsStart ) );
break;
case 'y': case 'yy': case 'year': case 'years':
returns = years;
break;
case 'd': case 'dd': case 'day': case 'days':
returns = ( ( end - start ) / ( 1000 * 60 * 60 * 24 ) );
break;
}
return returns;
}
使用法
var qtMonths = DateDiff('mm'、new Date( '2015-05-05')、new Date());
var qtYears = DateDiff('yy'、new Date( '2015-05-05')、new Date());
var qtDays = DateDiff('dd'、new Date( '2015-05-05')、new Date());
また
var qtMonths = DateDiff('m'、new Date( '2015-05-05')、new Date()); // m || y || d
var qtMonths = DateDiff('month'、new Date( '2015-05-05')、new Date()); //月|| 年|| 日
var qtMonths = DateDiff('months'、new Date( '2015-05-05')、new Date()); //月|| 年|| 日々
..。
var DateDiff = function (type, start, end) {
let // or var
years = end.getFullYear() - start.getFullYear(),
monthsStart = start.getMonth(),
monthsEnd = end.getMonth()
;
if(['m', 'mm', 'month', 'months'].includes(type)/*ES6*/)
return ( ( ( years * 12 ) - ( 12 - monthsEnd ) ) + ( 12 - monthsStart ) );
else if(['y', 'yy', 'year', 'years'].includes(type))
return years;
else if (['d', 'dd', 'day', 'days'].indexOf(type) !== -1/*EARLIER JAVASCRIPT VERSIONS*/)
return ( ( end - start ) / ( 1000 * 60 * 60 * 24 ) );
else
return -1;
}