how to show the date after a predefined date with jquery javascript - 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

Related

Conditionally convert multiple formats of Date and DateTime string into JavaScript Date Object

With this little utility JavaScript function below it can convert a basic Date string into a JavaScript Date object.
The date string can be in multiple formats like this...
stringToDate("17/9/2014", "dd/MM/yyyy", "/");
stringToDate("9/17/2014", "mm/dd/yyyy", "/");
stringToDate("9-17-2014", "mm-dd-yyyy", "-");
What I am hoping to do is expand it to also allow conditionally strings that also have a Time in them 09:12:49 09:12:49am, 09:12:49pm
So my function below where it creates the Date object with this line...
var formatedDate = new Date(dateItems[yearIndex], month, dateItems[dayIndex]);
would have to instead do something like...
var formatedDate = new Date(dateItems[yearIndex], month, dateItems[dayIndex], hours, minutes, seconds, milliseconds);
adding the hours, minutes, seconds, milliseconds only if they are detected in the original string.
Would such a task be possibble with this code?
// Convert Date String into JS Date Object
// Can parse multiple Date formats
// stringToDate("17/9/2014", "dd/MM/yyyy", "/");
// stringToDate("9/17/2014", "mm/dd/yyyy", "/");
// stringToDate("9-17-2014", "mm-dd-yyyy", "-");
function stringToDate(d, _format, _delimiter) {
if((d instanceof Date)){
return d;
}
var formatLowerCase = _format.toLowerCase();
var formatItems = formatLowerCase.split(_delimiter);
var dateItems = d.split(_delimiter);
var monthIndex = formatItems.indexOf("mm");
var dayIndex = formatItems.indexOf("dd");
var yearIndex = formatItems.indexOf("yyyy");
var month = parseInt(dateItems[monthIndex]);
month -= 1;
var formatedDate = new Date(dateItems[yearIndex], month, dateItems[dayIndex]);
return formatedDate;
}
I am aware of MomentJS, DateJS, DateJS Evolved, and SugarJS but I am trying to do this for a small utility library.

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.

Extract Month or Day or Year from Timestamp

I would like to know how to get a specific date format (date or month or day or year) from a timestamp. I am wanting to use this in a view with Backbone JS
var d = new Date(1397639141184);
alert(d.getDate() + '/' + (d.getMonth()+1) + '/' + d.getFullYear());
1.If it's JavaScript Timestamp(i.e., in milliseconds)
var date = new Date(13976391000);
var date = date.getDate(); //returns date (1 to 31) you can getUTCDate() for UTC date
var day = date.getMonth(); // returns 1 less than month count since it starts from 0
var year = date.getFullYear(); //returns year
// You can also use getHours(), getMinutes() and so on
2.If it's database timestamp - example 2013-03-14T02:15:00
var date = new Date('2013-03-14T02:15:00'); // Works in all browsers
var date = new Date('2013-10-18 08:53:14');// works in Chrome & doesn't work in IE/Mozilla
//note that its a string and you use the same above functions to get Date,month & year

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

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.

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