Why am I getting this error for JavaScript Date object? - javascript

I wrote the following code in JS
var d = new Date(2019, 9, 14);
var currentTime = d.getTime();
var daysToAdd = 3;
var secondsInDay = 86400;
var d = new Date(currentTime + daysToAdd*secondsInDay);
var year = d.getFullYear();
var month = ("0" + (d.getMonth())).slice(-2);
var day = ("0" + d.getDate()).slice(-2);
console.log('result in Y-M-D is: ' + year + '-' + month + '-' + day);
This outputs to result in Y-M-D is: 2019-09-14
What am I doing wrong here? How to I change this to output result in Y-M-D is: 2019-09-17 , which I originally intended to do

This happens because on this code
new Date(currentTime + daysToAdd*secondsInDay);
secondsInDay is a representation in seconds, and currentTime is represented in ms. If you multiply your secondsInDay by 1000 (to get the equivalent value in ms) you will get the desired date.

Instead of
var d = new Date(currentTime + daysToAdd*secondsInDay);
you can use
d.setDate(new Date().getDate()+3);

Youre problem is that the constructor of the date object uses MILISECONDS to calculate the date, and you're using SECONDS to add that 3 extra days. Instead of 86400 (seconds) you need to use the value 86400000 (miliseconds).
Goodbye!

You can add the number of days directly to d.getDate()
var d = new Date(2019, 9, 14);
var daysToAdd = 3;
var new_day = d.getDate() + daysToAdd;
var new_d = new Date(d.getFullYear(), d. getMonth(), new_day);
alert('result in Y-M-D is: ' + new_d.getFullYear() + '-' + new_d. getMonth() + '-' + new_day);

Related

round up hour difference in time to 2 decimal places with javascript

i'm trying to calculate the hours difference between to times using javascript. But i keep get the results NaN in the console. I get the current time using javascript and the late time from the localstorage
var log_time = localStorage.getItem('login_time')
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
var hour = currentDate.getHours(); // => 9
var minute= currentDate.getMinutes(); // => 30
var second= currentDate.getSeconds(); // => 51
console.log(log_time);
var today = day + "/" + month + "/" + year
var time = hour + ":" + minute + ":" + second
console.log(today+' '+time);
var date1 = (log_time);
var date2 = (today+' '+time);
var hours = Math.abs(date2 - date1) / 36e5;
console.log(hours.toFixed(2))
the time from the localstorage reads 15/7/2017 9:30:46
You need to change your date format little bit This may Help you and also parse those dates because those are stirng formate.
Working Fiddle
var log_time1 = '2017-07-15 09:30:46';//Examples of ISO format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS.
var log_time = new Date(log_time1)//string parsing date
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
var hour = currentDate.getHours(); // => 9
var minute= currentDate.getMinutes(); // => 30
var second= currentDate.getSeconds(); // => 51
var today = year + "-" + month + "-" + day
var time = hour + ":" + minute + ":" + second
var date1 = (log_time);
var test_date2 = (today+' '+time);
var date2= new Date(test_date2);//string parsing date
var hours = Math.abs(date2 - date1) / 36e5;
alert(hours.toFixed(2))
localStorage will store stringified version of any object, you need to parse it. If you converted it to milliseconds then also you need to parse it to number, it can save only string
var earlierDate = new Date( localStorage.getItem('login_time'))
// or var earlierDate = parseInt(localStorage.getItem('login_time'))
var currentDate = new Date()
var diff = currentDate - earlierDate;
Then convert diff to hour/minutes/seconds with your logic
Im not shure what youre trying to do here:
date2 - date1
These are booth strings, you cannot substract them. However you might convert them to milliseconds since 1970 which you could then do Math on:
var log_time = localStorage.getItem('login_time').split(" ");
log_time[0]=log_time[0].split("/").reverse().map((el,i)=>i?("0"+el).slice(-2):el).join("-");//5/4/2017 => 2017-04-05
log_time[1]=("0"+log_time[1]).slice(-8);// 9:30:10 => 09:30:10
var difference= new Date() - new Date(log_time.join("T"));
var hours=Math.floor(difference/(1000*60*60 /* one hour in ms */));
You may overthink the stored format. Its quite complicated to parse it properly.
http://jsbin.com/fofowayata/edit?console

Javascript setDate doesnt accept input

<code>
var d2 = $('#interval').val();
var new_date = new Date(get_start_date);
new_date.setDate(new_date.getDate() + d2);
var dd = new_date.getDate();
var mm = new_date.getMonth() + 1;
var y = new_date.getFullYear();
var endDate = y + '-' + mm + '-' + dd;
</code>
assuming d2 = 5
when im adding 5 dates to my current date, its not returning exact answer instead its adding months it becomes 2017-09-09
but when i just do this new_date.setDate(new_date.getDate() + 5) it gives me the correct output.
Just parse you d2 as an integer
var d2 = parseInt($('#interval').val(),10);
u can only use this arguments
new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
get_start_date is invailid ;)
var new_date = new Date(get_start_date);

Javascript n months after today

I am trying to get the day 90 days after today. This is my code:
var today = new Date();
var threeMonthsFromToday = new Date(today.setDate(today.getDate() + 90));
When I print threeMonthsFromToday, I get the correct date: 2017-04-24T15:17:42.641Z. However, when I try to reformat the date to be in the form dd/mm/yyyy using this code:
var day = ('0' + threeMonthsFromToday.getDate()).slice(-2);
var month = ('0' + threeMonthsFromToday.getMonth() + 1).slice(-2);
var year = threeMonthsFromToday.getFullYear();
var date = day + '/' + month + '/' + year;
I get a completely different and invalid date: 24/31/2017.
I have been debugging this for hours and still can't seem to figure what I am doing wrong.
Well, '0' + threeMonthsFromToday.getMonth() give you a string : "03" then you add 1 converted to string giving you "031" for month before slice.
Use this :
var month = ('0' + (threeMonthsFromToday.getMonth() + 1)).slice(-2);
You are missing the basic BODMAS rule here please modify your code as follows
var today = new Date();
var threeMonthsFromToday = new Date(today.setDate(today.getDate() + 90));
var day = ('0' + threeMonthsFromToday.getDate()).slice(-2);
var month = ('0' + (threeMonthsFromToday.getMonth() + 1)).slice(-2);
var year = threeMonthsFromToday.getFullYear();
var date = day + '/' + month + '/' + year;
the operations are performed from left to right, so month is getting converted to string before being added to a number. Including a bracket will first perform operation inside bracket and then make it a string
Can you use toLocaleString?
threeMonthsFromToday.toLocaleDateString('en-GB')
Below does the trick for you ...
getMonth() +1 before adding the "0" to it so that you get an arithematic +1
var today = new Date();
var threeMonthsFromToday = new Date(today.setDate(today.getDate() + 90));
var day = ('0' + threeMonthsFromToday.getDate()).slice(-2);
var month = ('0' + (threeMonthsFromToday.getMonth()+1)).slice(-2);
var year = threeMonthsFromToday.getFullYear();
var date = day + '/' + month + '/' + year;
console.log(date);
This should work.
var day = threeMonthsFromToday.getDate()
if(day < 10){
day = '0' + day
}
var month = threeMonthsFromToday.getMonth()+1
if(month<10){
month = '0' + month
}
var year = threeMonthsFromToday.getFullYear()
var date = day + '/' + month + '/' + year
Use Simple toLocaleDateString method
The toLocaleDateString() method returns a string with a language sensitive representation of the date portion of this date.
var today = new Date();
var threeMonthsFromToday = new Date(today.setDate(today.getDate() + 90));
var date = threeMonthsFromToday.toLocaleDateString();
console.log(date);
//result in console : "24/04/2017"
Try it out on your console.

Javascript : time addition

I have a begin date like this :
var beginDate = "29/04/2015";
var beginHour = "13:32";
I have some duration variables :
var hourDuration = "2";
var minuteDuration = "10";
I have to calculate the end date :
I my example, i attempt to get :
var endDate = "29/04/2015";
var endHour = "15:42";
But if the user set a long hour time for the duration, the endDate must take into account that the end will be another day.
Is there a way in JavaScript to calculate this times ?
without any libraries this would look like this:
var beginDate = "29/04/2015";
var beginHour = "13:32";
var hourDuration = "2";
var minuteDuration = "10";
var date = beginDate.split('/'), time = beginHour.split(':');
date = new Date(date[2], date[1] - 1, date[0], time[0], time[1]);
var newDate = new Date(+date + (hourDuration * 60 + +minuteDuration) * 60000);
var endDate = newDate.getDate() + '/' + (newDate.getMonth() + 1) + '/' + newDate.getFullYear();
var endHour = newDate.getHours() + ':' + newDate.getMinutes();
alert( endDate + ' ' + endHour);
But I would recommend to use momentjs
To have it really accurate you can use the "Date" object in Javascript. Be careful it is aware of the local timezone. The script underneath shows 17:42 instead of 15:42 if you are in GMT+2 (like me :)).
var beginDate = "29/04/2015";
var beginHour = "13:32";
var dateo = new Date(beginDate.split("/").reverse().join("-") + "T" + beginHour + ":00");
var hourDuration = "2";
var minuteDuration = "10";
var enddate = new Date(dateo.getTime() + (hourDuration * 3600000) + (minuteDuration * 60000 ));
alert(enddate);
You can use the built-in Date type from JavaScript:
var date= new Date(2015, 04, 29, 13, 32, 0);
date.setHours(beginDate.getHours()+2);
date.setMinutes(beginDate.getMinutes()+10);
alert( date.getDate() + '/' + date.getMonth() + 1 + '/' + date.getFullYear() +
" " + date.getHours() + ":" + date.getMinutes() );
Javascript has a built in Date object, that can parse RFC2822 compatible date-strings.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
However, your string does not conform to the RFC2822-specification(without prior alterations).
I would therefore recommend you to use momentjs. It's a very convenient library for date/time operations. For instance, to add two hours from your given date, you could type.
var timeString = '29/04/2015 13:32';
var time = moment(timeString, 'mm/dd/yyyy hh:ss').add(2, 'hour');
console.log(time.format('mm/dd/yyyy hh:ss') );
http://momentjs.com/docs/

How to get current date in jQuery?

I want to know how to use the Date() function in jQuery to get the current date in a yyyy/mm/dd format.
Date() is not part of jQuery, it is one of JavaScript's features.
See the documentation on Date object.
You can do it like that:
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var output = d.getFullYear() + '/' +
(month<10 ? '0' : '') + month + '/' +
(day<10 ? '0' : '') + day;
See this jsfiddle for a proof.
The code may look like a complex one, because it must deal with months & days being represented by numbers less than 10 (meaning the strings will have one char instead of two). See this jsfiddle for comparison.
If you have jQuery UI (needed for the datepicker), this would do the trick:
$.datepicker.formatDate('yy/mm/dd', new Date());
jQuery is JavaScript. Use the Javascript Date Object.
var d = new Date();
var strDate = d.getFullYear() + "/" + (d.getMonth()+1) + "/" + d.getDate();
Using pure Javascript your can prototype your own YYYYMMDD format;
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + "/" + (mm[1]?mm:"0"+mm[0]) + "/" + (dd[1]?dd:"0"+dd[0]); // padding
};
var date = new Date();
console.log( date.yyyymmdd() ); // Assuming you have an open console
In JavaScript you can get the current date and time using the Date object;
var now = new Date();
This will get the local client machine time
Example for jquery LINK
If you are using jQuery DatePicker you can apply it on any textfield like this:
$( "#datepicker" ).datepicker({dateFormat:"yy/mm/dd"}).datepicker("setDate",new Date());
function GetTodayDate() {
var tdate = new Date();
var dd = tdate.getDate(); //yields day
var MM = tdate.getMonth(); //yields month
var yyyy = tdate.getFullYear(); //yields year
var currentDate= dd + "-" +( MM+1) + "-" + yyyy;
return currentDate;
}
Very handy function to use it, Enjoy. You do not require any javascript framework. it just works in with plain javascript.
I know I am Late But This Is All You Need
var date = (new Date()).toISOString().split('T')[0];
toISOString() use built function of javascript.
cd = (new Date()).toISOString().split('T')[0];
console.log(cd);
alert(cd);
Since the question is tagged as jQuery:
If you are also using jQuery UI you can use $.datepicker.formatDate():
$.datepicker.formatDate('yy/mm/dd', new Date());
See this demo.
Here is method top get current Day, Year or Month
new Date().getDate() // Get the day as a number (1-31)
new Date().getDay() // Get the weekday as a number (0-6)
new Date().getFullYear() // Get the four digit year (yyyy)
new Date().getHours() // Get the hour (0-23)
new Date().getMilliseconds() // Get the milliseconds (0-999)
new Date().getMinutes() // Get the minutes (0-59)
new Date().getMonth() // Get the month (0-11)
new Date().getSeconds() // Get the seconds (0-59)
new Date().getTime() // Get the time (milliseconds since January 1, 1970)
See this.
The $.now() method is a shorthand for the number returned by the expression (new Date).getTime().
Moment.js makes it quite easy:
moment().format("YYYY/MM/DD")
this object set zero, when element has only one symbol:
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
This object set actual full time, hour and date:
function getActualFullDate() {
var d = new Date();
var day = addZero(d.getDate());
var month = addZero(d.getMonth()+1);
var year = addZero(d.getFullYear());
var h = addZero(d.getHours());
var m = addZero(d.getMinutes());
var s = addZero(d.getSeconds());
return day + ". " + month + ". " + year + " (" + h + ":" + m + ")";
}
function getActualHour() {
var d = new Date();
var h = addZero(d.getHours());
var m = addZero(d.getMinutes());
var s = addZero(d.getSeconds());
return h + ":" + m + ":" + s;
}
function getActualDate() {
var d = new Date();
var day = addZero(d.getDate());
var month = addZero(d.getMonth()+1);
var year = addZero(d.getFullYear());
return day + ". " + month + ". " + year;
}
HTML:
<span id='full'>a</span>
<br>
<span id='hour'>b</span>
<br>
<span id='date'>c</span>
JQUERY VIEW:
$(document).ready(function(){
$("#full").html(getActualFullDate());
$("#hour").html(getActualHour());
$("#date").html(getActualDate());
});
EXAMPLE
//convert month to 2 digits<p>
var twoDigitMonth = ((fullDate.getMonth().length+1) === 1)? (fullDate.getMonth()+1) : '0' + (fullDate.getMonth()+1);
var currentDate = fullDate.getFullYear()+ "/" + twoDigitMonth + "/" + fullDate.getDate();
console.log(currentDate);<br>
//2011/05/19
You can achieve this with moment.js as well.
Include moment.js in your html.
<script src="moment.js"></script>
And use below code in script file to get formatted date.
moment(new Date(),"YYYY-MM-DD").utcOffset(0, true).format();
FYI - getDay() will give you the day of the week... ie: if today is Thursday, it will return the number 4 (being the 4th day of the week).
To get a proper day of the month, use getDate().
My example below... (also a string padding function to give a leading 0 on single time elements. (eg: 10:4:34 => 10:04:35)
function strpad00(s)
{
s = s + '';
if (s.length === 1) s = '0'+s;
return s;
}
var currentdate = new Date();
var datetime = currentdate.getDate()
+ "/" + strpad00((currentdate.getMonth()+1))
+ "/" + currentdate.getFullYear()
+ " # "
+ currentdate.getHours() + ":"
+ strpad00(currentdate.getMinutes()) + ":"
+ strpad00(currentdate.getSeconds());
Example output: 31/12/2013 # 10:07:49If using getDay(), the output would be 4/12/2013 # 10:07:49
This will give you current date string
var today = new Date().toISOString().split('T')[0];
Try this....
var d = new Date();
alert(d.getFullYear()+'/'+(d.getMonth()+1)+'/'+d.getDate());
getMonth() return month 0 to 11 so we would like to add 1 for accurate month
Reference by : https://www.w3schools.com/jsref/jsref_obj_date.asp
you can use this code:
var nowDate = new Date();
var nowDay = ((nowDate.getDate().toString().length) == 1) ? '0'+(nowDate.getDate()) : (nowDate.getDate());
var nowMonth = ((nowDate.getMonth().toString().length) == 1) ? '0'+(nowDate.getMonth()+1) : (nowDate.getMonth()+1);
var nowYear = nowDate.getFullYear();
var formatDate = nowDay + "." + nowMonth + "." + nowYear;
you can find a working demo here
var d = new Date();
var today = d.getFullYear() + '/' + ('0'+(d.getMonth()+1)).slice(-2) + '/' + ('0'+d.getDate()).slice(-2);
The jQuery plugin page is down. So manually:
function strpad00(s)
{
s = s + '';
if (s.length === 1) s = '0'+s;
return s;
}
var now = new Date();
var currentDate = now.getFullYear()+ "/" + strpad00(now.getMonth()+1) + "/" + strpad00(now.getDate());
console.log(currentDate );
console.log($.datepicker.formatDate('yy/mm/dd', new Date()));
Using the jQuery-ui datepicker, it has a handy date conversion routine built in so you can format dates:
var my_date_string = $.datepicker.formatDate( "yy-mm-dd", new Date() );
Simple.
This is what I came up with using only jQuery. It's just a matter of putting the pieces together.
//Gather date information from local system
var ThisMonth = new Date().getMonth() + 1;
var ThisDay = new Date().getDate();
var ThisYear = new Date().getFullYear();
var ThisDate = ThisMonth.toString() + "/" + ThisDay.toString() + "/" + ThisYear.toString();
//Gather time information from local system
var ThisHour = new Date().getHours();
var ThisMinute = new Date().getMinutes();
var ThisTime = ThisHour.toString() + ":" + ThisMinute.toString();
//Concatenate date and time for date-time stamp
var ThisDateTime = ThisDate + " " + ThisTime;
You can do this:
var now = new Date();
dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");
// Saturday, June 9th, 2007, 5:46:21 PM
OR Something like
var dateObj = new Date();
var month = dateObj.getUTCMonth();
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
var newdate = month + "/" + day + "/" + year;
alert(newdate);
var d = new Date();
var month = d.getMonth() + 1;
var day = d.getDate();
var year = d.getYear();
var today = (day<10?'0':'')+ day + '/' +(month<10?'0':'')+ month + '/' + year;
alert(today);
I just wanted to share a timestamp prototype I made using Pierre's idea. Not enough points to comment :(
// US common date timestamp
Date.prototype.timestamp = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
var h = this.getHours().toString();
var m = this.getMinutes().toString();
var s = this.getSeconds().toString();
return (mm[1]?mm:"0"+mm[0]) + "/" + (dd[1]?dd:"0"+dd[0]) + "/" + yyyy + " - " + ((h > 12) ? h-12 : h) + ":" + m + ":" + s;
};
d = new Date();
var timestamp = d.timestamp();
// 10/12/2013 - 2:04:19
Get current Date format dd/mm/yyyy
Here is the code:
var fullDate = new Date();
var twoDigitMonth = ((fullDate.getMonth().toString().length) == 1)? '0'+(fullDate.getMonth()+1) : (fullDate.getMonth()+1);
var twoDigitDate = ((fullDate.getDate().toString().length) == 1)? '0'+(fullDate.getDate()) : (fullDate.getDate());
var currentDate = twoDigitDate + "/" + twoDigitMonth + "/" + fullDate.getFullYear();
alert(currentDate);
function createDate() {
var date = new Date(),
yr = date.getFullYear(),
month = date.getMonth()+1,
day = date.getDate(),
todayDate = yr + '-' + month + '-' + day;
console.log("Today date is :" + todayDate);
You can add an extension method to javascript.
Date.prototype.today = function () {
return ((this.getDate() < 10) ? "0" : "") + this.getDate() + "/" + (((this.getMonth() + 1) < 10) ? "0" : "") + (this.getMonth() + 1) + "/" + this.getFullYear();
}
This one-liner will give you YYYY-MM-DD:
new Date().toISOString().substr(0, 10)
'2022-06-09'

Categories