Javascript/jQuery decrementing an input date with datepicker [duplicate] - javascript

I need to decrement a Javascript date by 1 day, so that it rolls back across months/years correctly. That is, if I have a date of 'Today', I want to get the date for 'Yesterday'.
It always seems to take more code than necessary when I do this, so I'm wondering if there's any simpler way.
What's the simplest way of doing this?
[Edit: Just to avoid confusion in an answer below, this is a JavaScript question, not a Java one.]

var d = new Date();
d.setDate(d.getDate() - 1);
console.log(d);

var today = new Date();
var yesterday = new Date().setDate(today.getDate() -1);

day.setDate(day.getDate() -1); //will be wrong
this will return wrong day. under UTC -03:00, check for
var d = new Date(2014,9,19);
d.setDate(d.getDate()-1);// will return Oct 17
Better use:
var n = day.getTime();
n -= 86400000;
day = new Date(n); //works fine for everything

getDate()-1 should do the trick
Quick example:
var day = new Date( "January 1 2008" );
day.setDate(day.getDate() -1);
alert(day);

origDate = new Date();
decrementedDate = new Date(origDate.getTime() - (86400 * 1000));
console.log(decrementedDate);

setDate(dayValue)
dayValue is an integer from 1 to 31, representing the day of the month.
from https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/setDate
The behaviour solving your problem (and mine) seems to be out of specification range.
What seems to be needed are addDate(), addMonth(), addYear() ... functions.

Working with dates in JS can be a headache. So the simplest way is to use moment.js for any date operations.
To subtract one day:
const date = moment().subtract(1, 'day')

Related

How to get previous date in 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>

Change format date in JavaScript

I want to change the format in JavaScript, to be Year-month-day
I used this code to get 3 months before, but the format that was generated became like this 9/19/2019.
This my code:
var d = new Date();
d.setMonth(d.getMonth() - 3);
var x = d.toLocaleDateString();
console.log(x);
You can get Year, Month and Date and use string interpolation like below
var d = new Date();
d.setMonth(d.getMonth() - 3);
var formattedDate = `${d.getFullYear()}-${(d.getMonth() + 1)}-${d.getDate()}`;
console.log(formattedDate);
You can use momentjs, a lightweight and handy library for this purpose:
var d = moment(new Date()).subtract(3, 'months').format('dd-MMM-yyyy);
var x = d.toISOString().substring(0,10);
console.log(x);
//it will give you the format of y-m-d
You are using the toLocaleDateString() which will format to the result you received which is expected.
Reference Mozilla's Docs on Date() to get the right function for you there :)
Most instances you are able to just piece it together yourself similar to:
const date = `${date.getYear()}/${date.getMonth()}/${date.getDay()}`;
It's not a nice solution but there are a lot of restrictions with OOTB Date()

Javascript: check formatted date value against current date?

a text-input contains a german formatted date 15.09.2012
I simply use $('#wr_event_date').val() to query the value in the input-field.
I wonder how I can match that date agains "today"?
var eventDate = $('#wr_event_date').val();
// if eventDate is older than today as in "is over" doSomething();
So basically I want to check if the eventDate is older than today and if so I want to doSomething();
Ideas on that? Thank you in advance.
Unfortunately, you have to parse the date yourself. Then, fetch the current date with new Date(), reset the time part, and compare both dates:
var s = $('#wr_event_date').val().split(".");
var eventDate = new Date(s[2], s[1] - 1, s[0]);
var today = new Date();
today.setHours(0, 0, 0, 0); // reset time
if (eventDate.getTime() - today.getTime() < 0) { // event date is older than today
doSomething();
}
DEMO.
If you could use a third party library, then moment.js provides the functions to parse date strings and manipulate dates.
var parts = '15.09.2012'.split('.')
var date = Date.parse(parts[1], parts[0] - 1, parts[2]);
if (date - new Date().getTime() > 24 * 60 * 60 * 1000) ...
​

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

Javascript Date.UTC() function is off by a month?

I was playing around with Javascript creating a simple countdown clock when I came across this strange behavior:
var a = new Date(),
now = a.getTime(),
then = Date.UTC(2009,10,31),
diff = then - now,
daysleft = parseInt(diff/(24*60*60*1000));
console.log(daysleft );
The days left is off by 30 days.
What is wrong with this code?
Edit: I changed the variable names to make it more clear.
The month is zero-based for JavaScript.
Days and years are one-based.
Go figure.
UPDATE
The reason this is so, from the creator of JavaScript, is
JS had to "look like Java" only less so, be Java's dumb kid brother or boy-hostage sidekick. Plus, I had to be done in ten days or something worse than JS would have happened.
http://www.jwz.org/blog/2010/10/every-day-i-learn-something-new-and-stupid/#comment-1021
As Eric said, this is due to months being listed as 0-11 range.
This is a common behavior - same is true of Perl results from localtime(), and probably many other languages.
This is likely originally inherited from Unix's localtime() call.
(do "man localtime")
The reason is that days/years are their own integers, while months (as a #) are indexes of an array, which in most languages - especially C where the underlying call is implemented on Unix - starts with 0.
It's an old question but this is still a problem today (or a feature as some might say - and they are wrong).
JS is zero-based month, why? Because.
That means the months range from 0-11 (only the months, the others are normal)
How can you fix this? Add a month, obviously, BUUUUT:
Don't do this :
let date: Date = new Date();
date.setMonth(date.getMonth() + 1);
Why you might ask? Because it won't work as expected, Date in JS is terrible.
You have to make a ... let's call it not so beautiful function to translate the JS date to a normal date
formatJsDateToNormalDate(Date date): string | null {
if(date !== null) {
const realMonth: number = date.getMonth() + 1;
let month: string = (realMonth < 10) ? '0' + realMonth : String(realMonth);
let day: string = (date.getDate() < 10) ? '0' + date.getDate() : String(date.getDate());
return [date.getFullYear(), month, day].join('-');
} else {
return null;
}
Again, if you ask me this is the equivalent of hammering a screw, it's not the right way, but there is no right way here, it's a bug that has been going on for 27 years and more to come.
date1 = new Date();
//year, month, day [, hrs] [, min] [, sec]
date1 = new Date.UTC(date1.getFullYear(),date1.getMonth()+1,date1.getDate(),date1.getHours(),date1.getMinutes(),date1.getSeconds());
date2 = new Date();
date2 = date2.getTime();
alert(date1)
alert(date2)

Categories

Resources