how to get next day date and next month date using jquery - javascript

I want to get next day date and next month date using jquery
I tried like following :
//FOR NEXT DAY
var dateString = 'Dec 17, 2013'; // date string
var actualDate = new Date(dateString); // convert to actual date
var newDate = new Date(actualDate.getFullYear(), actualDate.getMonth(), actualDate.getDate()+1);
//FOR NEXT MONTH
var dateString = 'Dec 17, 2013'; // date string
var actualDate = new Date(dateString); // convert to actual date
var newDate = new Date(actualDate.getFullYear(), actualDate.getMonth(), actualDate.getDate()+30);
but which is not good practice :(
please guide how can i get next day date and next month date using jquery function or any good method?

In order to avoid dealing with the number of days in a month, the leap years and so on, use the Moment.js library (http://momentjs.com)
var d = new Date("2012/02/05");
var m = moment(d);
m.add('days', 1);
m.add('months', 1);
d = m.toDate();
Consider also that adding one month will not add the same amount of time depending on the current month.

Related

how to show the date after a predefined date with jquery javascript

I have a string which contains a date like this: 2021-05-20
Now I am looking for the next day after this date so i am looking for 2021-05-21
How can I do that?
var date = '2021-05-20';
var dayafter = ??? // should be 2021-05-21
// below gives me the date after today
var date = new Date();
date.setDate(date.getDate() + 1);
console.log(date);
// but i need the day after a predefined date

Fastest method of building a timestamp of the current hour

I'm looking for the fastest method to build a timestamp which represents the current hour starting from the current instant (in general, starting from a timestamp)
Currently I'm doing the following:
var d = new Date();
var year = d.getUTCFullYear();
var month = d.getUTCMonth();
var day = d.getUTCDate();
var hour = d.getUTCHours();
d = new Date(year, month, day, hour);
console.log(d);
console.log(d.getTime());
Is it possible to avoid the second invocation of Date?
If I understand you correctly you want the timestamp of the beginning of the current hour. Then you could simply set the minutes and seconds to 0 in your first Date Object:
var d = new Date();
d.setMinutes(0,0);
console.log(d);
console.log(d.getTime());
You could make it a oneliner, since setMinutes() already returns a timestamp:
var timestamp = new Date().setMinutes(0,0);
Not sure why you're doing that twice, you really don't need to.
var d = new Date();
console.log(d.getHours());
// or
console.log(d.getTime() );

Why does initializing a date object fail when I use a variable instead of integers or a string?

I am trying to create a new date object initialized to a date passed in from another function. The program will not know the desired date in advance, but let's say the date is January 1, 2017.
Successful:
var newYear = new Date(2017, 0, 1);
Logger.log(newYear.toISOString());
//logs 2017-01-01T08:00:00.000Z
Unsuccessful:
var date = "2017, 0, 1";
var newYear = new Date(date);
Logger.log(newYear.toISOString());
//throws "Error, date range is invalid."
Unsuccessful:
var date = "2017-0-1";
var newYear = new Date(date);
Logger.log(newYear.toISOString());
//throws "Error, date range is invalid."
Edit: Just before posting I figured it out. I hope no one minds me posting and answering my own question-- maybe you can answer it better!
Even though a string looks like a series of integers separated by commas, and even though Javascript is a loosely typed language, they are not the same.
Solution:
var year = 2017;
var month = 0; //don't forget months go from 0-11
var day = 1;
var newYear = new Date(year, month, day);
Logger.log(newYear.toISOString());
//logs 2017-01-01T08:00:00.000Z
To parse a date in the form of "2017-03-04":
var givenDate = "2017-3-04"
var date = givenDate.split("-");
var Year = date[0];
var Month = date[1]-1;
var Day = date[2];
var newYear = new Date(Year, Month, Day);
Logger.log(newYear.toISOString());
//logs 2017-01-01T08:00:00.000Z
Note: to output date in your local time zone, instead of "toISOString()", which reports the time as GMT/ISO time (on most browsers), you can use "toDateString()" to output a more readable form which is reflective of your local time zone.

JavaScript - Convert date stirng yyyyMMddHHmmss to date object yyyy-MM-dd HH:mm:ss

I have this date : 2014071109080706ICT
I need to convert it to Date object in JS
I tried to create new object new Date("2014071109080706ICT") but I get error Invalid date
I also tried cut date string to "20140711090807" and create new Date object but it always generate error : Invalid date
How can i do it ?
You can try to use moment.js .
http://momentjs.com
There are some examples in docs page. One of them is:
moment("2010-10-20 4:30 +0000", "YYYY-MM-DD HH:mm Z");
http://momentjs.com/docs/#/parsing/
You can try:
moment("20140711090807+0600", "YYYYMMDDHHmmssZZ");
I think "06ICT" is the timezone info.
You just need to slice the string for each segment and create the date object based on those parts.
var str = "20140711090807";
var year = str.substring(0, 4);
var month = str.substring(4, 6);
var day = str.substring(6, 8);
var hour = str.substring(8, 10);
var minute = str.substring(10, 12);
var second = str.substring(12, 14);
var date = new Date(year, month-1, day, hour, minute, second);
PS: month index is between 0 and 11 so you need to subtract it by 1.

compare string with today's date in JavaScript

I've got a string from an input field which I use for date with a format like this 25-02-2013. Now I want to compare the string with today's date. I want to know if the string is older or newer then today's date.
Any suggestions?
<script type="text/javascript">
var q = new Date();
var m = q.getMonth()+1;
var d = q.getDay();
var y = q.getFullYear();
var date = new Date(y,m,d);
mydate=new Date('2011-04-11');
console.log(date);
console.log(mydate)
if(date>mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
</script>
Exact date comparsion and resolved bug from accepted answer
var q = new Date();
var m = q.getMonth();
var d = q.getDay();
var y = q.getFullYear();
var date = new Date(y,m,d);
mydate=new Date('2011-04-11');
console.log(date);
console.log(mydate)
if(date>mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
You can use a simple comparison operator to see if a date is greater than another:
var today = new Date();
var jun3 = new Date("2016-06-03 0:00:00");
if(today > jun3){
// True if today is on or after June 3rd 2016
}else{
// Today is before June 3rd
}
The reason why I added 0:00:00 to the second variable is because without it, it'll compare to UTC (Greenwich) time, which may give you undesired results. If you set the time to 0, then it'll compare to the user's local midnight.
Using Javascript Date object will be easier for you. But as the Date object does not supports your format i think you have to parse your input string(eg: 25-02-2013) with '-' to get date month and year and then use Date object for comparison.
var x ='23-5-2010';
var a = x.split('-');
var date = new Date (a[2], a[1] - 1,a[0]);//using a[1]-1 since Date object has month from 0-11
var Today = new Date();
if (date > Today)
alert("great");
else
alert("less");
If your date input is in the format "25-02-2013", you can split the string into DD, MM and YYYY using the split() method:
var date_string="25-02-2013";
var day = parseInt(date_string.split("-")[0]);
var month= parseInt(date_string.split("-")[1]);
var year = parseInt(date_string.split("-")[2]);
The parseInt() function is used to make the string into an integer. The 3 variables can then be compared against properties of the Date() object.
The most significant points which needs to be remembered while doing date comparison
Both the dates should be in same format to get accurate result.
If you are using date time format and only wants to do date comparison then make sure you convert it in related format.
Here is the code which I used.
var dateNotifStr = oRecord.getData("dateNotif");
var today = new Date();
var todayDateFormatted = new Date(today.getFullYear(),today.getMonth(),today.getDate());
var dateNotif=new Date(dateNotifStr);
var dateNotifFormatted = new Date(dateNotif.getFullYear(),dateNotif.getMonth(),dateNotif.getDate());
Well, this can be optimized further but this should give you clear idea on what is required to make dates in uniform format.
Here's my solution, getDay() doesn't work like some people said because it grabs the day of the week and not the day of the month. So instead you should use getDate like I used below
var date = new Date();
var m = date.getMonth();
var d = date.getDate();
var y = date.getFullYear();
var todaysDate = formateDate(new Date(y,m,d));
console.log("Todays date is: " + todaysDate)
const formateDate = (assignmentDate) => {
const date = new Date(assignmentDate)
const formattedDate = date.toLocaleDateString("en-GB", {
day: "numeric",
month: "long",
year: "numeric"
})
return formattedDate
}
The function below is just to format the date into a legible format I could display to my users
<script type="text/javascript">
// If you set the timezone then your condition will work properly,
// otherwise there is a possibility of error,
// because timezone is a important part of date function
var todayDate = new Date().toLocaleString([], { timeZone: "Asia/Dhaka" }); //Today Date
var targetDate = new Date('2022-11-24').toLocaleString([], { timeZone: "Asia/Dhaka" });
console.log('todayDate ==', todayDate); // todayDate == 10/31/2022, 12:15:08 PM
console.log('targetDate ==', targetDate); // targetDate == 11/24/2022, 6:00:00 AM
if(targetDate >= todayDate)
{
console.log("Today's date is small");
}
else
{
console.log("Today's date is big")
}
</script>

Categories

Resources