47
var dateObj = new Date();
var val = dateObj.getTime();
//86400 * 1000 * 3  Each day is 86400 seconds
var  days = 259200000;

val = val + days;
dateObj.setMilliseconds(val);
val = dateObj.getMonth() + 1 + "/" + dateObj.getDate() + "/" + dateObj.getFullYear();
alert(val);

現在の日付を取得し、それに3ミリ秒を追加して、現在の日付から3日後に日付スタンプを表示しようとしています。たとえば、今日が2012年10月9日の場合、2012年10月12日と言いたいと思います。

この方法は機能していません。私は何ヶ月も何日も休んでいます。助言がありますか?

4

5 に答える 5

74

時間を追加するには、現在の日付を取得し、ミリ秒単位で特定の時間を追加してから、次の値で新しい日付を作成します。

// get the current date & time (as milliseconds since Epoch)
const currentTimeAsMs = Date.now();

// Add 3 days to the current date & time
//   I'd suggest using the calculated static value instead of doing inline math
//   I did it this way to simply show where the number came from
const adjustedTimeAsMs = currentTimeAsMs + (1000 * 60 * 60 * 24 * 3);

// create a new Date object, using the adjusted time
const adjustedDateObj = new Date(adjustedTimeAsMs);

これをさらに説明するには; 動作しない理由dataObj.setMilliseconds()は、dateobjのミリ秒PROPERTYを指定された値(0〜999の値)に設定するためです。オブジェクトの日付はミリ秒単位では設定されません。

// assume this returns a date where milliseconds is 0
dateObj = new Date();

dateObj.setMilliseconds(5);
console.log(dateObj.getMilliseconds()); // 5

// due to the set value being over 999, the engine assumes 0
dateObj.setMilliseconds(5000);
console.log(dateObj.getMilliseconds()); // 0

参照:
Date.now()
new Date()
Date.setMilliseconds()

于 2012-10-09T08:24:44.410 に答える
19

これを試して:

var dateObj = new Date(Date.now() + 86400000 * 3);

JavaScriptの日付はミリ秒単位で正確であるため、10001秒です。
1分に60秒、1時間に60分、1日に24時間あります。

したがって、1日は次1000 * 60 * 60 * 24のようになります。これは86400000ミリ秒です。

Date.now()ミリ秒単位で正確な現在のタイムスタンプを返します。
そのタイムスタンプに3日分のミリ秒を追加して、に渡しますnew Date()。これは、数値で呼び出されると、指定Dateされたタイムスタンプからオブジェクトを作成します。

于 2012-10-09T08:25:28.450 に答える
9

javascriptで日付を計算する必要がある場合は、moment.jsを使用してください。

moment().add(3, 'days').calendar();
于 2012-10-09T08:24:17.917 に答える
6

このコードを使用する

var dateObj = new Date(); 
var val = dateObj.getTime(); 
//86400 * 1000 * 3  Each day is 86400 seconds 
var  days = 259200000; 

val = val + days; 
dateObj = new Date(val); // ********important*********//
val = dateObj.getMonth() + 1 + "/" + dateObj.getDate() + "/" + dateObj.getFullYear(); 
alert(val);
于 2012-10-09T08:26:27.257 に答える
2

より任意Dateのオブジェクト(以外.now())に対してこれを実行する場合は、次のようなものを使用できます。

const initialDate = new Date("March 20, 2021 19:00");

const millisecondsToAdd = 30 * 24 * 60 * 60 * 1000; //30 days in milliseconds

const expiryDate = new Date(initialDate.valueOf() + millisecondsToAdd);
于 2021-03-20T19:30:00.957 に答える