Javascript date shows a day before [duplicate] - javascript

This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 4 years ago.
I'm using mydatepicker in my Angular application. When user clicks a specific date I'm getting the selected date. But I want to have a date format like this.
20180320
or
2018-03-20
So what I did was to convert as follows.
onDateChange(event) {
this.selectDate = event.jsdate.toISOString().slice(0,10)
}
This helps me to get my format. But it shows a day before. That means , if a user selects 2018-03-20 from calendar my selectDate = 2018-03-19
I can do that using moment , but for this project I'm not using for some reasons.Could someone help me to correct this?

Try this to account for timezone
onDateChange(event){
var localDate = new Date(event.jsdate.getTime() - event.jsdate.getTimezoneOffset() * 60000);
this.selectDate = localDate.toISOString().slice(0,10);
}

toISOString is always in UTC+0 time. If you console.log it, you should see a Z on the end. That means GMT.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString

Just try this with prototype function
Date.prototype.getDDMMYYYY = function () {
var date = JSON.stringify(this.getDate()).length == 1 ? ("0" + this.getDate()) : this.getDate();
var month = JSON.stringify(this.getMonth()).length == 1 ? ("0" + this.getMonth()) : this.getMonth();
var year = this.getFullYear();
return year+"-"+month+"-"+date;
}
and Just replace this code
onDateChange(event){
this.selectDate = event.jsdate.getDDMMYYYY()
}

Related

Increment Month in JavaScript removes the DATE format using setMonth() [duplicate]

This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 4 years ago.
Below is my JavaScript Code to try and create a Maximum date where the user can't book past so many months into the future:
var x= 12;
var arriveDate = "28/11/2018"
var currentDate = new Date();
var a_date = new Date(arriveDate);
var max_month = currentDate.setMonth(currentDate.getMonth()+ x);
if (arriveDate === ""){
$("#arrive_date_error").html("Please don't leave this field blank");
}
else if (a_date < currentDate){
console.log("Please don't select a date in the past")
}
else if (a_date > max_month){
console.log("date in future")
}
The last else if never seems to work no matter what month/day/year I try. I decided to use console.log(max_month) to see what month it was creating and it returned:
1574953488195
Rather than the correct format:
Thu Nov 28 2019 15:04:48 GMT+0000
What am I doing wrong and why is it changing the format when I try to change the month of the date object?
setMonth mutates the currentDate, it does not return a new date. You probably want to clone the date and set the months of that cloned one:
var max_month = new Date(+currentDate);
max_month.setMonth(max_month.getMonth() + x);

Comparing the current date with a date received from an api response [duplicate]

This question already has answers here:
How to calculate date difference in JavaScript? [duplicate]
(24 answers)
Closed 4 years ago.
I want to compare the date I receive from an API to the current date and if it exceeds 14 days. The date I receive is in this format.
"date": "2018-08-07T14:17:24+02:00"
You can use the library date-fns to calculate this too. It has a smaller bundle size than Moment.
function exceedsDays(date, numberOfDays) {
var today = dateFns.startOfToday();
var diff = dateFns.differenceInDays(today, dateFns.parse(date));
return diff > numberOfDays;
}
var date = "2018-08-07T14:17:24+02:00";
var result = exceedsDays(date, 14);
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.29.0/date_fns.min.js"></script>
let dateFrom = new Date("2018-08-07T14:17:24+02:00").getTime();
let today = new Date().getTime();
let days14 = 1000 * 60 * 60 * 24 * 14;
if(today - dateFrom > days14){ }
If you go with momentjs you can do something like that. This will return you a boolean. You can reuse later this function to maybe check if more than 30 days etc. Just need to change the second argument. The first one is your date you want to check. By default moment() return now, this is the reason we don't need to create a date for now.
const oldDate = '2018-08-07T14:17:24+02:00';
function exceedNumOfDays(date, numOfDays) {
return moment().diff(new Date(date), 'days') > numOfDays;
}
exceedNumOfDays(oldDate, 14)
I put the code on codesandbox, you can see the console at the bottom left. https://codesandbox.io/s/oo967v83xq

Invalid Date when using Date.parse() [duplicate]

This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 4 years ago.
I have a date-picker on my web application that produces the following output 25-04-2018 16:50:
It is: day-month-year hour:minute.
The idea is that I'll have two input-text, and the first date has to be before the second date. Otherwise, swap the dates.
I want to compare two dates in this format, so I try to create a Date object:
<input onchange="date()" type="text" readonly id="datetimepicker_1"/>
<input onchange="date()" type="text" readonly id="datetimepicker_2"/>
<script>
function date() {
var start = document.getElementById("datetimepicker_1");
var end = document.getElementById("datetimepicker_2");
if (start.value.trim() && end.value.trim()) {
var dateStart = new Date(start.value);
var dateEnd = new Date(end.value);
if (dateStart > dateEnd){
document.getElementById("datetimepicker_1").value = end.value;
document.getElementById("datetimepicker_2").value = start.value;
}
}
</script>
But I have the following error: Invalid Date. How I can compare these dates?
It looks like JavaScript isn't tolerating the format of your date.
You have the date in format of "Day-Month-Year Hour-Minute" Or DD-MM-YYYY
I was able to get the following code to work in two scenarios; having the date in the format : "Year-Month-Day Hour-Minute" or "Month-Day-Year Hour Minute"
This code is very poorly written but I think it illustrates the idea.
function DatePicker()
{
var datestart = new Date("2018-04-25 16:50"); //or 04-25-2018 16:50
console.log(datestart);
var datestart2 = new Date("2018-04-25 16:55"); //or 04-25-2018 16:50
console.log(datestart2);
if (datestart < datestart2)
{
console.log("success");
} else {
console.log("failed");
}
}
DatePicker();
I recognize that different countries in the world use different date formats. So to solve your issue I would recommend using "Moment.js" so you are able to format the date to your liking or needs as laid out in the Stack Overflow question and answer linked below.
DD/MM/YYYY Date format in Moment.js

Format date with "/" to "-" with javascript [duplicate]

This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 7 years ago.
I have this Javascript function that takes X number of days and returns a date in the past
var GetDateInThePastFromDays = function (days) {
var today = new Date();
_date = new Date(today.getFullYear(), today.getMonth(), today.getDate() - days);
return _date.toLocaleDateString();
}
That works absolutely fine, but it returns the date as 06/01/2016 but I want it returned as 06-01-2016 but I can't seem to find out how to do it correctly.
.toLocaleDateString() returns a string formatted according to the user's locale, meaning the format will match whatever is set on the user's machine. For me, that's 06/01/2016 but for an American it might be 01/06/2016 (because they're weird like that).
You should define your own format if you want a fixed one:
function pad(n) {return (n<10 ? "0" : "")+n;}
return pad(_date.getDate()) + "-" + pad(_date.getMonth()+1) + "-" + _date.getFullYear();

Date Comparison Using Javascript [duplicate]

This question already has answers here:
Compare two dates with JavaScript
(44 answers)
Closed 8 years ago.
I have two date strings in DDMMYYYY format. say startdate="18/02/2013" and enddate ="26/02/2013".
How can I compare these dates. I want enddate to be greater than or equal to startdate
Thanks for Your Time.
I'm a fan of moment.js and consider it a core part of my toolkit whenever I have to deal with dates and times - especially when any form of parsing or formatting is involved.
You're free to do the parsing by hand and invoke the appropriate Date constructor manually, but consider the following which I consider simple and intuitive.
var startDate = moment.parse("18/02/2013", "DD/MM/YYYY");
var endDate = moment.parse("26/02/2013", "DD/MM/YYYY");
if (endDate.isAfter(startDate)) {
// was after ..
}
Does this solution suits your needs (demo : http://jsfiddle.net/wared/MdA3B/)?
var startdate = '18/02/2013';
var d1 = startdate.split('/');
d1 = new Date(d1.pop(), d1.pop() - 1, d1.pop());
var enddate = '26/02/2013';
var d2 = enddate.split('/');
d2 = new Date(d2.pop(), d2.pop() - 1, d2.pop());
if (d2 >= d1) {
// do something
}
Keep in mind that months begin with 0. MDN doc :
month : Integer value representing the month, beginning with 0 for January to 11 for December.
var d1 = Date.parse("18/02/2013");
var d2 = Date.parse("26/02/2013");
if (d1 > d2) {
alert ("do something");
}

Categories