Javascript日期对象中的更新小时数返回负数

时间:2018-07-06 10:44:52

标签: javascript date

我如何确定这个数字,我只想小时数

var newDate = new Date();

var defaultHours = newDate.getHours();

var myHours = newDate.setHours(5);

console.log(defaultHours - myHours);
//resulte => -1530851451556

2 个答案:

答案 0 :(得分:2)

setHours将小时数设置为传递的值,并返回更新的UNIX时间。因此,请勿在设置小时数时设置值myHours。而是在设置后获取它。

MDN Docs供参考。

正如@musefan在问题注释中指出的那样,您可以直接减去而不是设置/获取开销。

var newDate = new Date("2018-07-06T10:50:22.138Z");
var defaultHours = newDate.getHours(); // 16
newDate.setHours(5); //Sets hours to 5 but returns the  date as timestamp 1530834622138
var myHours = newDate.getHours();
console.log(defaultHours - myHours);

答案 1 :(得分:0)

/* // =====================================================================
* *
* * * How I Can Fix This Numbers (1530834622138), I Want Just Hours Numbers
* *
*/ // =====================================================================


var newDate = new Date();

var defaultHours   = newDate.getHours(); 
var defaultMinutes = newDate.getMinutes();
var defaultSeconds = newDate.getSeconds();

// ========================= Start My Set Date =========================
newDate.setHours(12); //Sets hours to 12 but returns the  date as timestamp 1530834622138
var myHours = newDate.getHours();

newDate.setMinutes(12); //Sets Minutes to 12 but returns the  date as timestamp 1530834622138
var myMinutes = newDate.getMinutes();

newDate.setSeconds(0); //Sets seconds to 0 but returns the  date as timestamp 1530834622138
var mySeconds = newDate.getSeconds();
// ========================= End My Set Date =========================

// ============================== Result =============================
var resultHours   = defaultHours   - myHours;
var resultMinutes = defaultMinutes - myMinutes;
var resultSeconds = defaultSeconds - mySeconds;
// ============================== Result =============================

// ============================== If Statement =============================
defaultHours    = defaultHours   < 10 ? "0" + defaultHours : defaultHours;
defaultMinutes  = defaultMinutes < 10 ? "0" + defaultMinutes : defaultMinutes;
defaultSeconds  = defaultSeconds < 10 ? "0" + defaultSeconds : defaultSeconds;

myHours    = myHours   < 10 ? "0" + myHours : myHours;
myMinutes  = myMinutes < 10 ? "0" + myMinutes : myMinutes;
mySeconds  = mySeconds < 10 ? "0" + mySeconds : mySeconds;

resultHours    = resultHours   < 10 ? "0" + resultHours : resultHours;
resultMinutes  = resultMinutes < 10 ? "0" + resultMinutes : resultMinutes;
resultSeconds  = resultSeconds < 10 ? "0" + resultSeconds : resultSeconds;
// ============================== If Statement =============================

console.log("Real Time:       " + defaultHours + ":" + defaultMinutes + ":" + defaultSeconds);

console.log("My Time:         " + myHours + ":" + myMinutes + ":" + mySeconds);

console.log("Clalculate Time: " + resultHours + ":" + resultMinutes + ":" + resultSeconds);