Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript New Date()

Tags:

javascript

I have the following JavaScript code but for some reason time is not including minutes:

var austDay = $("#<%= hiddenFieldTime.ClientID %>").val().split(" ");

var year = austDay[0];

var months = austDay[1];

var days = austDay[2];

var time = austDay[3];

var timeUntil = new Date(parseInt(year), parseInt(months), 
                         parseInt(days), parseInt(time));

When I debug using firebug these are my value:

$("#ctl00_hiddenFieldTime").val() = "2011, 5, 6, 14:20:00"

year = "2011,"

months = "5,"

days = "6,"

time = "14:20:00"

timeUntil = Date {Mon Jun 06 2011 14:00:00 GMT-0400 (Eastern Daylight Time)}

As you can see, timeUntil is set to 14:00:00 instead of 14:20:00

like image 375
DAK Avatar asked Apr 07 '11 13:04

DAK


2 Answers

parseInt(time) is the problem

Here are the few dates initialization format

var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
like image 68
niksvp Avatar answered Sep 28 '22 13:09

niksvp


According to the Mozilla documentation for Date, the following constructors are supported:

new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day [, hour, minute, second, millisecond ])

This means that in your constructor, when you pass parseInt(time), that parameter is only used for the hour parameter. You need to pass a separate parameter for minutes, and yet another one if you happen to want seconds.


Also, you should always pass a base parameter to parseInt, like so:
parseInt(hours, 10)

Otherwise when you go to parse a value with a leading 0 such as parseInt('08'), the value will be interpreted as an octal number.

like image 43
Justin Ethier Avatar answered Sep 28 '22 13:09

Justin Ethier