How to get previous date in javascript - javascript

I have one date but i want to get previous date from that.How we can do using javascript or momentjs?
Demo:https://stackblitz.com/edit/js-ykswiz?file=index.js
date format dd-mm-yyyy.
Example:
var date1=new Date("08-06-2020");
console.log("Prev Date="+date1.getDate() - 1);// Prev Date=07-06-2020
var date2=new Date("01-06-2020");
console.log("Prev Date="+date2.getDate() - 1);// Prev Date=31-05-2020
var date3=new Date("01-01-2021");
console.log("Prev Date="+date3.getDate() - 1);// Prev Date=31-12-2020
Is it possible in javascript?

first, if you pass a string to the new Date() function, it should be in this format new Date('MM-dd-yyyy')
so the first 2 digits represent the month
the second 2 digits represent the date
the next 4 digits represent the year
so new Date("08-06-2020") means August 06, 2020 not June 08, 2020
to get the previous day of some date, we can use the moment to subtract 1 day like the following
var date1 = new Date('08-06-2020'); // Aug 06, 2020
var date11 = moment(date1).subtract(1, 'days').format('DD-MM-YYYY');
console.log(`date1 >> ${date1}`);
console.log(`date11 >> ${date11}`);
var date2 = new Date('01-06-2020'); // Jan 06, 2020
var date22 = moment(date2).subtract(1, 'days').format('DD-MM-YYYY');
console.log(`date2 >> ${date2}`);
console.log(`date22 >> ${date22}`);
hope it helps

Since the issue with the Date constructor is explained and solved by one of the above answers, this solution is for the ones who use moment() instead of new Date() 👇
var date = moment('08-06-2020', 'DD-MM-yyyy');
var previousDate = moment(date).subtract(1, 'days'); //derive the previous date
var nextDate = moment(date).add(1, 'days'); //derive the next date
console.log(previousDate.format('DD-MM-yyyy')); //output => 07-06-2020
console.log(nextDate.format('DD-MM-yyyy')); //output => 09-06-2020
👇 read more about adding and subtracting dates in moment.js
https://momentjs.com/docs/#/manipulating/subtract/
https://momentjs.com/docs/#/manipulating/add/
👇 read more about formatting dates in moment.js
https://momentjs.com/docs/#/parsing/string-format/

you can use the setDate and getDate functions;
var date1=new Date("08-06-2020");
date1.setDate(date1.getDate() - 1);
console.log("Prev Date="+date1.getDate());// Prev Date=08-05-2020
hope its what you asked for.
btw, in this format tha previous date will be 08-05-2020 since the default is mm-dd-yyyy

You could achieve this using momentjs. Use the moment constructor to parse the input string then use the subtract() to subtract the specified number of days from the moment object. Resultant can be formatted according to your requirements
let arr = ["08-06-2020", "01-06-2020", "01-01-2021"];
let prevDates = arr.map(item => {
let momentItem = moment(item, "DD-MM-YYYY");
let prevDay = momentItem.subtract(1, "days");
return prevDay.format("DD-MM-YYYY");
});
console.log(prevDates);
<script src="https://momentjs.com/downloads/moment.js"></script>

Related

Javascript and setMonth behaving unexpectedly

I am doing datObj.setMonth(1), but the month is being set to March? Isn't 1 supposed to be February? I'm using Chrome 79.
Here's part of code meant to parse dates such as YYYY-MM-DD HH:MM:SS (because safari can't do that natively)
var date = "2020-02-02 23:59:00"
if (typeof date == 'string')
{
var dateParts = date.split(/[:-\s]+/);
if (dateParts.length == 6)
{
dateObj = new Date();
dateObj.setYear(dateParts[0]);
var m = dateParts[1] - 1;
console.log('m= ' + m);
dateObj.setMonth(m);
console.log('after setmonth, date= ' + dateObj);
dateObj.setDate(dateParts[2]);
dateObj.setHours(dateParts[3]);
dateObj.setMinutes(dateParts[4]);
dateObj.setSeconds(dateParts[5]);
}
}
console.log(dateObj);
alert(dateObj);
Your problem, as you figured, is that you're setting the month while the day is still 30. While you could work around that by using setFullYear and pass year, month and day at once, you really should just construct the whole Date object with the right values in the first place:
dateObj = new Date(dateParts[0], dateParts[1]-1, dateParts[2], dateParts[3], dateParts[4], dateParts[5]);
or rather using UTC as the timezone:
dateObj = new Date(Date.UTC(dateParts[0], dateParts[1]-1, dateParts[2], dateParts[3], dateParts[4], dateParts[5]));
Just figured this out before I submitted. Today is January 30th, 2020. I can't change the month to February, because there is no February 30th. So, the code breaks either on the 29th or the 30th day of the month.
In JavaScript, it is advisable to do
dateObj.setMonth(monthNum -1, dayNum)
to set the day and month at the same time to avoid this problem

Javascript newdate function unexpected output

I am confused by the result of the following script and I don't understand why it is what it is:
enddate = '01-02-2020'; //euro format dd-mm-yyyy
datesplit = enddate.split("-");
console.log("datesplit: ", datesplit); //[ '01', '02', '2020' ]
console.log(datesplit[2]); // 2020
console.log(datesplit[1]); // 02
console.log(datesplit[0]); // 01
enddate1 = new Date(datesplit[2],datesplit[1],datesplit[0]);
console.log("enddate 1", enddate1); //output: 2020-03-01T05:00:00.000Z , but I'm expecting 2020-02-01T00:00:00.000Z
That last console log output is what I can't understand. I would appreciate an explanation of why the result is what it is.
JavaScript treats the month as zero-based. So you'll have to -1 your month value to get the right result. As #RobG said, you should use new Date(Date.UTC(...)) to get your date in UTC
let endDate = '01-02-2020' // dd-mm-yyyy;
let [day, month, year] = endDate.split('-');
// Months are zero-based, so -1 to get the right month
month = month - 1;
console.log(day); // '01'
console.log(month);// 1
console.log(year); // '2020'
let newDate = new Date(Date.UTC(year, month, day));
console.log(newDate) // "2020-02-01T00:00:00.000Z"
Given that the other posts seem to have helped you get the right month, have you tried using .toISOString method on the Date object to get the right UTC offset?
The docs on MDN state that the timezone is always zero UTC offset.
You can check Mozilla Documentation
You will see that January is 0, February is 1, and so on. So that's how date works in JavaScript.
You need to convert your month value to Number and then make it "-1". So something like this:
new Date(datesplit[2], (parseInt(datesplit[1], 10) - 1), datesplit[0])

Add Number of months to a Date in a text field

function addDays(){
var myDate =document.getElementById('treatdate');
var numberOfDaysToAdd = document.getElementById('resultdays');
var tset = numberOfDaysToAdd.value;
var result1 = myDate.value.addMonths(parseInt(tset));
var pldate= moment(result1).format('YYYY-MM-DD');
return pldate; }
'treatdate' is an id for a treatment date which is pulled from my database. Thanks in advance.
You can always use moment.js library for Date manipulations. http://momentjs.com/
For your problem you can do the following.
function addDays(){
var datefrmDb = $('#treatdate').val();
var monthstoadd= $('#resultdays').val();
var new_date = (moment(datefrmDb, "YYYY-MM-DD").add('months', monthstoadd)).format("YYYY-MM-DD");
return new_date;
}
If your date format is yyyy-MM-dd
var myDate = new Date(document.getElementById('treatdate').value);
this will a date and time.
Example:
var dd = new Date("2014-02-02 11:11:11")
console log
Sun Feb 02 2014 11:11:11 GMT+0000 (GMT Standard Time)
See if this snippet can help you understand how to manipulate dates. To change/add the months to a Date() object you can use the setMonth() method.
numberOfMonthsToAdd = 5; // the number of months that you want to add
date = new Date(); // creating a Date object
date.setMonth(numberOfMonthsToAdd); // adding the number of months
Note that you may add numbers beyond 12 - the object handles the date, and jumps to the next year.

What is the proper way to create a timestamp in javascript with date string?

I have date format returned as 05-Jan, 12-feb etc.. when i convert current date using date object in javascript . I did something like this
var curr = new Date(),
curr_year = curr.getFullYear(),
curr_month = curr.getMonth(),
curr_day = curr.getDay(),
today = new Date(curr_year, curr_month, curr_day, 0, 0, 0, 0);
console.log(today);
Here the today is returned as invalid date i needed the create a timestamp which should not include minutes secs and millisecs as zero for date comparison of month and date alone based on that i can categories .Is there way to dynamically create a date and compare those dates for given format.
And when i try to convert my date string using date object it returns year as 2001. how can i compare dates based upon current year.
For eg: in php i have used mktime to create a date dynamically from given date format and compare those results. Any suggestion would be helpful. Thanks.
You can leverage the native JS Date functionality to get human-readable date strings for time stamps.
var today = new Date();
console.log( today.toDateString() ); // Outputs "Mon Feb 04 2013"
Date comparison is also built in.
var yesterday = new Date();
yesterday.setDate( yesterday.getDate() - 1);
console.log( yesterday.toDateString() ); // Outputs "Sun Feb 03 2013"
console.log( yesterday < today ); //Outputs true
You can use the other built-in methods to fine-tune this comparison to be/not be sensitive to minutes/seconds, or to set all those to 0.
You said that you used mktime() in php, so what about this?
change to this :
var curr = new Date(),
curr_year = curr.getFullYear(),
curr_month = curr.getMonth()+1,
curr_day = curr.getDay(),
today = curr_month+'/'+curr_day+'/'+curr_year;
console.log(today);
(getMonth()+1 is because January is 0)
change the :
today = curr_month+'/'+curr_day+'/'+curr_year;
to whatever format you like.
I have found a way to convert the date into timestamp i have tried as #nbrooks implemented but .toDateString has built in date comparison which works for operator < and > but not for == operator to do that i have used Date.parse(); function to achieve it. Here it goes..
var curr = new Date(),
curr_year = curr.getFullYear(),
curr_month = curr.getMonth(),
curr_day = curr.getDate(),
today = new Date(curr_year, curr_month, curr_day, 0,0,0,0);
var dob = new Date('dob with month and date only'+curr_year);
if(Date.parse(dob) == Date.parse(today)){
//Birthdays....
}
This method can be used to create a timestamp for dynamically created date.Thanks for your suggestions.

convert iso date to milliseconds in javascript

Can I convert iso date to milliseconds?
for example I want to convert this iso
2012-02-10T13:19:11+0000
to milliseconds.
Because I want to compare current date from the created date. And created date is an iso date.
Try this
var date = new Date("11/21/1987 16:00:00"); // some mock date
var milliseconds = date.getTime();
// This will return you the number of milliseconds
// elapsed from January 1, 1970
// if your date is less than that date, the value will be negative
console.log(milliseconds);
EDIT
You've provided an ISO date. It is also accepted by the constructor of the Date object
var myDate = new Date("2012-02-10T13:19:11+0000");
var result = myDate.getTime();
console.log(result);
Edit
The best I've found is to get rid of the offset manually.
var myDate = new Date("2012-02-10T13:19:11+0000");
var offset = myDate.getTimezoneOffset() * 60 * 1000;
var withOffset = myDate.getTime();
var withoutOffset = withOffset - offset;
console.log(withOffset);
console.log(withoutOffset);
Seems working. As far as problems with converting ISO string into the Date object you may refer to the links provided.
EDIT
Fixed the bug with incorrect conversion to milliseconds according to Prasad19sara's comment.
A shorthand of the previous solutions is
var myDate = +new Date("2012-02-10T13:19:11+0000");
It does an on the fly type conversion and directly outputs date in millisecond format.
Another way is also using parse method of Date util which only outputs EPOCH time in milliseconds.
var myDate = Date.parse("2012-02-10T13:19:11+0000");
Another option as of 2017 is to use Date.parse(). MDN's documentation points out, however, that it is unreliable prior to ES5.
var date = new Date(); // today's date and time in ISO format
var myDate = Date.parse(date);
See the fiddle for more details.
Yes, you can do this in a single line
let ms = Date.parse('2019-05-15 07:11:10.673Z');
console.log(ms);//1557904270673
Another possible solution is to compare current date with January 1, 1970, you can get January 1, 1970 by new Date(0);
var date = new Date();
var myDate= date - new Date(0);
Another solution could be to use Number object parser like this:
let result = Number(new Date("2012-02-10T13:19:11+0000"));
let resultWithGetTime = (new Date("2012-02-10T13:19:11+0000")).getTime();
console.log(result);
console.log(resultWithGetTime);
This converts to milliseconds just like getTime() on Date object
var date = new Date()
console.log(" Date in MS last three digit = "+ date.getMilliseconds())
console.log(" MS = "+ Date.now())
Using this we can get date in milliseconds
var date = new Date(date_string);
var milliseconds = date.getTime();
This worked for me!
if wants to convert UTC date to milliseconds
syntax : Date.UTC(year, month, ?day, ?hours, ?min, ?sec, ?milisec);
e.g :
date_in_mili = Date.UTC(2020, 07, 03, 03, 40, 40, 40);
console.log('miliseconds', date_in_mili);
In case if anyone wants to grab only the Time from a ISO Date, following will be helpful. I was searching for that and I couldn't find a question for it. So in case some one sees will be helpful.
let isoDate = '2020-09-28T15:27:15+05:30';
let result = isoDate.match(/\d\d:\d\d/);
console.log(result[0]);
The output will be the only the time from isoDate which is,
15:27

Categories

Resources