admin管理员组文章数量:1134246
The date returned by date picker is off by one day. Is it a problem in my code or is it a bug?
The date sent to date_picker is 2012-03-21. The date returned by datepicker is Tue Mar 20 2012.
var end_date = end_calendar.getFormatedDate("%Y-%m-%d");
end_date = $.datepicker.formatDate('D M dd yy', new Date(end_date));
I've struggled with this issue also and discovered a salient point on the issue so I thought I'd add a code snippet that displays the problem.
The following code only:
- sets the
valueAsDate
property - reads the
valueAsDate
property
But on my systems it always shows wrong date when I read the property.
function initDate(){
document.querySelector("#mainDate").valueAsDate = new Date();
}
function showDate(){
alert(document.querySelector("#mainDate").valueAsDate);
}
<body onload="initDate()">
<h2>Reading the property we set gets different value</h2>
<p> Notice that the code only:
<ul><li>sets the value using valueAsDate property</li>
<li>reads the same property valueAsDate </li>
</ul>
<input type="date" id="mainDate">
<button onclick="showDate()">show date</button>
</body>
The date returned by date picker is off by one day. Is it a problem in my code or is it a bug?
The date sent to date_picker is 2012-03-21. The date returned by datepicker is Tue Mar 20 2012.
var end_date = end_calendar.getFormatedDate("%Y-%m-%d");
end_date = $.datepicker.formatDate('D M dd yy', new Date(end_date));
I've struggled with this issue also and discovered a salient point on the issue so I thought I'd add a code snippet that displays the problem.
The following code only:
- sets the
valueAsDate
property - reads the
valueAsDate
property
But on my systems it always shows wrong date when I read the property.
function initDate(){
document.querySelector("#mainDate").valueAsDate = new Date();
}
function showDate(){
alert(document.querySelector("#mainDate").valueAsDate);
}
<body onload="initDate()">
<h2>Reading the property we set gets different value</h2>
<p> Notice that the code only:
<ul><li>sets the value using valueAsDate property</li>
<li>reads the same property valueAsDate </li>
</ul>
<input type="date" id="mainDate">
<button onclick="showDate()">show date</button>
</body>
Here's a snapshot of the value I get that shows that I always get a date that is one day less than the value that the control displays.
Share Improve this question edited Mar 13, 2023 at 13:08 raddevus 9,0368 gold badges75 silver badges97 bronze badges asked Mar 1, 2012 at 1:24 user823527user823527 3,70217 gold badges69 silver badges111 bronze badges 6 | Show 1 more comment16 Answers
Reset to default 39It is not the datepicker,
console.log(new Date('2012-03-21')); //prints Tue Mar 20 2012 20:00:00 GMT-0400 (Eastern Daylight Time)
The Javascript Date object can accept one of the following syntax as below,
- new Date()
- new Date(milliseconds)
- new Date(dateString)
- new Date(year, month, day [, hour, minute, second, millisecond ])
So in your case it is going to call the dateString and parse. So try appending the time as below,
new Date ('2012-03-21T00:00:00') //should return you Wed Mar 21 2012
DEMO
or Better to use as below,
new Date (2012, 2, 21).
year - Integer value representing the year. For compatibility (in order to avoid the Y2K problem), you should always specify the year in full; use 1998, rather than 98.
month - Integer value representing the month, beginning with 0 for January to 11 for December.
day - Integer value representing the day of the month (1-31).
This is not a bug, but definitely confusing.
Most of the answers on this page are confused and contain some mis-information.
The real issue is in how the javascript Date
object parses date strings.
The best answer I have found is this stack-O answer. Check out its' excellent write-up.
Below is a very pertinent comment from the answer mentioned above. (credit: @Mizstik)
All of this is due to the behavior of the underlying Date.parse() trying to follow ISO 8601. When the date string follows the yyyy-mm-dd format, it's assumed to be ISO 8601 with implicit UTC 00:00. When the string deviates from the format (e.g. mm-dd-yyyy or slash instead of hyphen), it falls back to the looser parser according to RFC 2822 which uses local time when the timezone is absent. Admittedly, this will all be quite arcane to an average person.
Seems to be a bug. If the string sent to Date()
is formatted as 2012/03/21
instead of 2012-03-21
. The date seems right.
You can add the difference to the date which will essentially ignore whatever the timezone is.
d.setTime( d.getTime() + d.getTimezoneOffset()*60*1000 );
It is happening due to difference in timezone with date format- yyyy-mm-dd
new Date ('2015/07/10'); // returns: "Fri Jul 10 2015 00:00:00 GMT-0700 (Pacific Daylight Time)"
new Date ('2012-07-10'); // returns: "Thu Jul 09 2015 17:00:00 GMT-0700 (Pacific Daylight Time)"
yyyy/mm/dd
- is not considering timezone while calculating local time.But
yyyy-mm-dd
- is considering timezeone while calculating local time in java script date function.
This can be reproducible when client(browser) and server time zones are different and having timezone/date difference by 1 day.
You can try this on your machine by changing time to different time zones where time gap b/w should be >=12 hours.
I don't know why this works but what I've found is whether you use forward slashes or dashes affects the answer. Take a look.
new Date ('2012/03/21'); // returns: "Wed Mar 21 2012 00:00:00 GMT-0500 (CDT)"
new Date ('2012-03-21'); // returns: "Tue Mar 20 2012 19:00:00 GMT-0500 (CDT)" WHA!
So to fix my issue I did a simple regex on my input date to always replace the first three dashes with forward slashes.
var strInputValue = control.value, // <-- get my date string
dteCurrent;
strInputValue = strInputValue.replace(/-/, '/') // replace 1st "-" with "/"
.replace(/-/, '/'); // replace 2nd "-" with "/"
dteCurrent = new Date(strInputValue);
I did a very quick google search for why this would happen and no answer. But this should fix your issue. All you have to do is replace the dashes with forward slashes before you pass them to where you want them.
Edit: sorry I didn't notice the already accepted answer before posting, please disregard this answer.
After trying many solutions the following code worked for me taken from (https://stackoverflow.com/a/14006555/1736785)
function createDateAsUTC(date) {
return new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()));
}
To avoid getting one day off, I replaced the - with / using .replace() on the creation of the date variable like this
var startDate = new Date(data[3].replace(/-/g, '\/'));
I don't have the reputation to comment, but Venu M gave me good insight. My project is having the same issue where depending on the syntax of my date input, the date returns as input or off one day. Expanding out and looking at the full date format, my different input date formats are returning in either UTC or my local time zone, depending on the syntax. I am using Moment JS to parse my dates then returning a date object for validation with Breeze. I have either an input modal or a table in which to edit, so now I need to make sure both are parsed and validated identically. I suggest verifying your date object is being created the same way regardless of its input syntax or input location.
var myDate = $.datepicker.parseDate("yy-mm-dd", "2013-10-21");
..//do whatever with myDate now
check your spelling of .getFormatedDate
and change it to .getFormattedDate
it's a trivial change but tweak it and see if any fixture results.
After experiencing the same issue and landing on this page, it turned out in my case it was caused by invalid labeling of the days. I started the week on Monday, instead of Sunday. I hope this helps somebody.
In my case I was getting this issue because the time zone of my country is UTC+01:00
but in my DatePicker
(I'm using MUI with react) was GMT+0200
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { DatePicker, TimePicker } from '@mui/x-date-pickers';
import TextField from '@mui/material/TextField';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';
import { DateTime, Settings } from 'luxon';
dayjs.extend(utc);
dayjs.extend(timezone);
Settings.defaultZone = 'Europe/London';
function name(
{
handleSubmit,
day, setDay,
time, setTime
}
{
// Handle date change and convert to UTC DateTime
const handleDateChange = (newDate) => {
if (newDate) {
const utcDate = DateTime.fromJSDate(newDate.toDate(), { zone: 'europe/london' });
setDay(utcDate);
} else {
setDay(null);
}
};
// Handle time change and convert to UTC DateTime
const handleTimeChange = (newTime) => {
if (newTime) {
const utcTime = DateTime.fromJSDate(newTime.toDate(), { zone: 'europe/london' });
setTime(utcTime);
} else {
setTime(null);
}
};
return (
<LocalizationProvider dateAdapter={AdapterDayjs}>
<DatePicker
className='day'
// value={day ? day.toJSDate() : null} // Convert Luxon DateTime to JavaScript Date
//value={day}
onChange={handleDateChange}
textField={(params) => <TextField {...params} />}
<TimePicker
// value={time ? time.toJSDate() : null} // Convert Luxon DateTime to JavaScript Date
onChange={handleTimeChange}
textField={(params) => <TextField {...params} />}
/>
/>
</LocalizationProvider>
);
Note: Might include some syntax errors. Manage accordingly
As said Javascript January equals 0 so this would work for datepicker or input type date.
end_date = end_date.split('-');
end_date = new Date(end_date[0],Number(end_date[1])-1,end_date[2]);
Try out this,
ranges": {
'Today': [moment().hours(0).minutes(0).seconds(0).milliseconds(0), moment().hours(23).minutes(59).seconds(59).milliseconds(999)],
'Yesterday': [moment().subtract(1, 'days').hours(0).minutes(0).seconds(0).milliseconds(0), moment().subtract(1, 'days').hours(23).minutes(59).seconds(59).milliseconds(999)],
'Last 7 Days': [moment().subtract(6, 'days').hours(0).minutes(0).seconds(0).milliseconds(0), moment().hours(23).minutes(59).seconds(59).milliseconds(999)],
'Last 30 Days': [moment().subtract(29, 'days').hours(0).minutes(0).seconds(0).milliseconds(0), moment().hours(23).minutes(59).seconds(59).milliseconds(999)],
'This Month': [moment().startOf('month').hours(0).minutes(0).seconds(0).milliseconds(0), moment().endOf('month').hours(23).minutes(59).seconds(59).milliseconds(999)],
'Last Month': [moment().subtract(1, 'month').startOf('month').hours(0).minutes(0).seconds(0).milliseconds(0), moment().subtract(1, 'month').endOf('month').hours(23).minutes(59).seconds(59).milliseconds(999)]
},
ranges": { 'Today': [moment().hours(0).minutes(0).seconds(0).milliseconds(0), moment().hours(23).minutes(59).seconds(59).milliseconds(999)], 'Yesterday': [moment().subtract(1, 'days').hours(0).minutes(0).seconds(0).milliseconds(0), moment().subtract(1, 'days').hours(23).minutes(59).seconds(59).milliseconds(999)], 'Last 7 Days': [moment().subtract(6, 'days').hours(0).minutes(0).seconds(0).milliseconds(0), moment().hours(23).minutes(59).seconds(59).milliseconds(999)], 'Last 30 Days': [moment().subtract(29, 'days').hours(0).minutes(0).seconds(0).milliseconds(0), moment().hours(23).minutes(59).seconds(59).milliseconds(999)], 'This Month': [moment().startOf('month').hours(0).minutes(0).seconds(0).milliseconds(0), moment().endOf('month').hours(23).minutes(59).seconds(59).milliseconds(999)], 'Last Month': [moment().subtract(1, 'month').startOf('month').hours(0).minutes(0).seconds(0).milliseconds(0), moment().subtract(1, 'month').endOf('month').hours(23).minutes(59).seconds(59).milliseconds(999)] },
本文标签: javascriptdatepicker date off by one dayStack Overflow
版权声明:本文标题:javascript - datepicker date off by one day - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736828918a1954617.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
document.write(new Date('2012-03-21'))
printsTue Mar 20 2012 20:00:00 GMT-0400 (Eastern Daylight Time)
for me. Leap year bug? – No Results Found Commented Mar 1, 2012 at 1:322012-03-21
and2012/03/21
toDate()
gives results that are 4 hours apart. – No Results Found Commented Mar 1, 2012 at 1:38