[英]What is the proper way to create a timestamp in javascript with date string?
當我使用javascript中的日期對象轉換當前日期時,我將日期格式返回為05年1月,2月2日等。 我做了這樣的事情
var curr = new Date(),
curr_year = curr.getFullYear(),
curr_month = curr.getMonth(),
curr_day = curr.getDay(),
today = new Date(curr_year, curr_month, curr_day, 0, 0, 0, 0);
console.log(today);
在這里今天返回為無效日期,我需要創建一個時間戳,該時間戳不應該包括分鍾秒和毫秒作為零,僅用於基於月份和日期的日期比較(基於我可以進行分類)。有沒有辦法動態創建日期並進行比較給定格式的日期。 當我嘗試使用日期對象轉換日期字符串時,它返回的年份為2001。我如何根據當前年份比較日期。 例如:在php中,我已經使用mktime根據給定的日期格式動態創建日期,並比較這些結果。 任何建議都會有所幫助。 謝謝。
您可以利用本機JS Date功能來獲取人類可讀的時間戳日期字符串。
var today = new Date();
console.log( today.toDateString() ); // Outputs "Mon Feb 04 2013"
日期比較也是內置的。
var yesterday = new Date();
yesterday.setDate( yesterday.getDate() - 1);
console.log( yesterday.toDateString() ); // Outputs "Sun Feb 03 2013"
console.log( yesterday < today ); //Outputs true
您可以使用其他內置方法來微調此比較,使其對分鍾/秒不敏感,或者將所有這些都設置為0。
你說,你在使用PHP mktime(),那么,關於這個 ?
更改為此:
var curr = new Date(),
curr_year = curr.getFullYear(),
curr_month = curr.getMonth()+1,
curr_day = curr.getDay(),
today = curr_month+'/'+curr_day+'/'+curr_year;
console.log(today);
(getMonth()+ 1是因為一月為0)
更改:
today = curr_month+'/'+curr_day+'/'+curr_year;
您喜歡的任何格式。
我已經找到一種將日期轉換為時間戳的方法,我嘗試使用@nbrooks實現,但是.toDateString具有內置的日期比較功能,該功能適用於運算符<和>,但不適用於==運算符,我已經使用Date.parse();
功能來實現它。 來了
var curr = new Date(),
curr_year = curr.getFullYear(),
curr_month = curr.getMonth(),
curr_day = curr.getDate(),
today = new Date(curr_year, curr_month, curr_day, 0,0,0,0);
var dob = new Date('dob with month and date only'+curr_year);
if(Date.parse(dob) == Date.parse(today)){
//Birthdays....
}
此方法可用於為動態創建的日期創建時間戳。謝謝您的建議。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.