I have written these two javascript functions:
function getDateFromDateAtHourOfDay(date, hour)
{
var year = date.getFullYear();
var month = date.getMonth();
var day = date.getDate();
var newDate = new Date(year, month, day, hour, 0, 0);
return (newDate);
}
and
function getDateDescriptionFromDate(date)
{
var year = date.getFullYear();
var month = date.getMonth();
var day = date.getDate();
return ( (day < 10 ? ("0" + day) : (day)) + "." + (month < 10 ? ("0" + month) : (month)) + "." + year);
}
The first one should return a new date with the same year/month/day but with a different hour of the day (e.g. switch 2015-04-05 15:00 to 2015-04-05 16:00).
The second one should just return a date-string in the format dd.MM.yyyy.
Now if I call
var selectedDate = new Date(); // normally function parameter
var startDate = getDateFromDateAtHourOfDay(selectedDate, hour);
document.getElementById("dateLabel").innerHTML = getDateDescriptionFromDate(startDate);
Where hour is a function parameter and for example 15 (tested with alert), in my "dateLabel" it says 05.01.2015. But if I do
alert (selectedDate);
the result is: Sun Apr 05 2015 15:52:26 GMT+0200 (CEST) => now.
selectedDate is not modified between the calls (alert and set the innerHTML).
I think the two functions do not do what I suppose them to, but maybe you find the mistake.
Thank you !
EDIT:
I tried this code:
selectedDate = new Date();
alert(selectedDate); // Sun Apr 05 2015 16:36:07 GMT+0200 (CEST)
var startDate = getDateFromDateAtHourOfDay(selectedDate, hour);
alert(hour); // 8
alert(startDate); // Thu Mar 05 2015 08:00:00 GMT+0100 (CET)
document.getElementById("datumLabel").innerHTML = getDateDescriptionFromDate(startDate); // 05.01.2015
I don't know why you're surprised by what selectedDate is returning. You have only set it to new Date() (now). Nothing in the code is manipulating this variable from the point of creation.
You are, however, manipulating the value and storing the change in startDate and dateLabel.innerHTML. You would only notice the formatting though since the second function strips any change in "time" (done by the first function).
So, in short: You create a date (now), change the time, then format it to only show date.
var selectedDate = new Date();
//selectedDate value = the date and time right now
var startDate = getDateFromDateAtHourOfDay(selectedDate, hour);
//startDate value = whatever selectedDate was + hours sent as parameter
document.getElementById("dateLabel").innerHTML = getDateDescriptionFromDate(startDate);
//Formatted value of startDate, to only show date
As per comment:
You're missing that month in javascript is zero-based. So you'll have to do something like:
var month = date.getMonth() + 1; //in the second function
function getDateFromDateAtHourOfDay(date, hour)
{
var year = date.getFullYear();
var month = date.getMonth();
var day = date.getDate();
var newDate = new Date(year, month, day, hour, 0, 0);
return (newDate);
}
function getDateDescriptionFromDate(date)
{
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
return ( (day < 10 ? ("0" + day) : (day)) + "." + (month < 10 ? ("0" + month) : (month)) + "." + year);
}
var selectedDate = new Date(); // normally function parameter
var startDate = getDateFromDateAtHourOfDay(selectedDate, 15);
document.getElementById("dateLabel").innerHTML = 'Your current system date: ' + getDateDescriptionFromDate(startDate);
<div id="dateLabel"></div>
If you try this, this should give you save value for your alert and Label, the value you are using for the Label is different than the value you are trying to use alert on.
selectedDate = new Date();
alert(selectedDate); // Sun Apr 05 2015 16:36:07 GMT+0200 (CEST)
var startDate = getDateFromDateAtHourOfDay(selectedDate, hour);
alert(hour); // 8
alert(startDate); // Thu Mar 05 2015 08:00:00 GMT+0100 (CET)
var startDateDesc = getDateDescriptionFromDate(startDate);
alert(startDateDesc) // 05.01.2015
document.getElementById("datumLabel").innerHTML = startDateDesc; // 05.01.2015
Related
I want to change this date to be formatted to DD-MM-YY
new Date(new Date().setDate(new Date().getDate() + 7)))
Current result: Thu Sep 15 2022 02:16:38 GMT+0200 (Central European Summer Time)
Wanted result: 15-09-22
I suggest solving the problem step by step.
Check the Date object documentation. There are methods that return the day, month, and year.
Add leading "0" when you need it. For instance, like this: ${value < 10 ? '0' : ''}${value}.
Concatenate the strings:
`${dayString}-${monthString}-${date.getFullYear()}`
let date = new Date()
date.setDate(date.getDate() + 7);
const day = date.getDate();
const month = date.getMonth();
const dayString = `${day < 10 ? '0' : ''}${day}`;
const monthString = `${month < 10 ? '0' : ''}${month}`;
const formatted = `${dayString}-${monthString}-${date.getFullYear()}`;
const event = new Date(new Date().setDate(new Date().getDate() + 7));
var day = event.getDate();
var month = event.getMonth();
var year = event.getFullYear();
var date = day + '-' + month + '-' + year;
date.toString();
I did find a fix for my issues no more comments are necessary
startDate = "2019-03-07 (목) 12:00";
var year = startDate.slice(0,4);
var month = startDate.slice(5,7);
var day = startDate.slice(8,10);
var hour = startDate.slice(15,17);
var minute = startDate.slice(18,20);
var selEndDatetime = new Date(year, month, day, hour, minute);
console.log(selEndDatetime);
I want to see "Tue Mar 07 2019 12:00:00 GMT+0900 (한국 표준시)", but console shows me the message "Sun Apr 07 2019 12:00:00 GMT+0900 (한국 표준시)".
What is wrong this code and how can I modify it to get the desired output?
The month starts at 0. You need to parse month from string to integer and minus 1 when creating a date instance.
startDate = "2019-03-07 (목) 12:00";
var year = startDate.slice(0,4);
var month = parseInt(startDate.slice(5,7))
var day = startDate.slice(8,10);
var hour = startDate.slice(15,17);
var minute = startDate.slice(18,20);
var selEndDatetime = new Date(year, month - 1, day, hour, minute);
console.log(selEndDatetime);
You can simply pass the startDate string as an argument to the Date in order to create selEndDatetime
Code:
const startDate = '2019-03-07 (목) 12:00';
const selEndDatetime = new Date(startDate);
console.log(selEndDatetime);
I am trying to set an end date for a JSON object. The end date equals 30 days after the start date. Sometimes this returns the correct date, sometimes it doesn't.
Here is the GetDateSchedulerFormatted function
GetDateSchedulerFormatted(date) {
function pad(s) { return (s < 10) ? '0' + s : s; }
var d = new Date(date);
// yyy-MM-dd
return [pad(d.getDate()), pad(d.getMonth() + 1), d.getFullYear()].join('/') + " " + pad(d.getHours()) + ":" + pad(d.getMinutes());
}
In this example the code returns the correct date
//activity.startDate = 2017-07-02T00:00:00-08:00
var startDate = this.GetDateSchedulerFormatted(activity.startDate); //start date 07/02/2017 00:00 d/m/yyy
var newDate = new Date(startDate); // returns Tue Aug 01 2017 00:00:00 GMT-0700 (Pacific Daylight Time) also 1 day off
var endDate = this.GetDateSchedulerFormatted(new Date(newDate.setTime(newDate.getTime() + 30 * 86400000))); //returns correct date 01/08/2017 00:00 d/m/yyyy
In this next example it returns the date 1 year off
//activity.startDate = 2016-12-12T00:00:00-08:00
var startDate = this.GetDateSchedulerFormatted(activity.startDate); //returns 12/12/2016 00:00 d/m/yyy
var newDate = new Date(startDate); // returns Wed Jan 11 2017 00:00:00 GMT-0800 1 month ahead
var endDate = this.GetDateSchedulerFormatted(new Date(newDate.setTime(newDate.getTime() + 30 * 86400000))); //returns 11/01/2017 00:0 d/m/yyy
In this example the same exact date is returned
//activity.startDate = 2017-02-01T00:00:00-08:00
var startDate = this.GetDateSchedulerFormatted(activity.startDate); //returns 01/02/2017 00:00 d/m/yyy
var newDate = new Date(startDate); // returns Wed Feb 01 2017 00:00:00 GMT-0800
var endDate = this.GetDateSchedulerFormatted(new Date(newDate.setTime(newDate.getTime() + 30 * 86400000))); //returns 01/02/2017 00:00 the same date, it's not 30 days ahead
Then in this final example I get NaN/NaN/NaN NaN:NaN
//activity.startDate = 2017-02-25T00:00:00-08:00
var startDate = this.GetDateSchedulerFormatted(activity.startDate); //returns 25/02/2017 00:00 d/m/yyy
var newDate = new Date(startDate); // returns invalid date
var endDate = this.GetDateSchedulerFormatted(new Date(newDate.setTime(newDate.getTime() + 30 * 86400000))); //returns NaN/NaN/NaN NaN:NaN
I have also tried new Date(Date.parse(startDate));
You really don't need a library. To add one month to a date is fairly straight forward, starting with:
date.setMonth(date.getMonth() + 1);
This maintains the time associated with the date, even over daylight saving boundaries, but can push the date beyond the end of the following month, e.g. adding 1 month to Jan 31 gives 31 Feb which goes to 2 or 3 March (depending on if it's a leap year or not).
So there needs to be a check that if the date isn't the same, it's rolled over a month so set it to the last day of the previous month. Written as a function to add an arbitrary number of months:
function addMonths(date, months) {
var d = date.getDate();
date.setMonth(date.getMonth() + +months);
if (date.getDate() != d) {
date.setDate(0);
}
return date;
}
// Add 12 months to 29 Feb, 2016
var d = new Date(2016,1,29)
console.log(addMonths(d, 12).toString()); // 28 Feb 2017
Adding is even easier, see Add +1 to current date which is easily adapted to add any number of days (which means this question is really a duplicate).
So, back to your code.
Here is the GetDateSchedulerFormatted function
function GetDateSchedulerFormatted(date) {
function pad(s) {
return (s < 10) ? '0' + s : s;
}
var d = new Date(date);
// yyy-MM-dd
return [pad(d.getDate()),
pad(d.getMonth() + 1),
d.getFullYear()
].join('/') + " " +
pad(d.getHours()) + ":" +
pad(d.getMinutes());
}
// In this example the code returns the correct date
var activity = {};
activity.startDate = '2017-07-02T00:00:00-08:00';
var startDate = GetDateSchedulerFormatted(activity.startDate); //start date 07/02/2017 00:00 d/m/yyy
var newDate = new Date(startDate); // returns Tue Aug 01 2017 00:00:00 GMT-0700 (Pacific Daylight Time) also 1 day off
var endDate = GetDateSchedulerFormatted(new Date(newDate.setTime(newDate.getTime() + 30 * 86400000))); //returns
correct date 01/08/2017
Your issue is that you start with a valid ISO 8601 formatted string, '2017-07-02T00:00:00-08:00' but then reformat it into your own format in your own timezone (something like '02/07/2017 00:00' if your timezone is -0800), then parse that with the Date constructor, which is a very bad idea. It's likely treated as 7 February so I don't know how you can say it returns the correct date when you started with 2 July. And adding 1 month should be 2 August, not 1 August (though you did add 30 days rather than 1 month). Lastly, if you cross a daylight saving boundary, you may lose or pick up an hour so the date may be 23:00 the day before or go from 00:00 to 01:00.
Note that you have:
07/02/2017 00:00 d/m/yyy
^^^^^^^
which is not 2 July, it's 7 February.
The rest of your issues are similar.
Anyhow, if you're happy with using a library, fine. Just thought I'd point out where you'd gone wrong.
Here's your code adapted so it runs here, showing the errors:
function GetDateSchedulerFormatted(date) {
function pad(s) {
return (s < 10) ? '0' + s : s;
}
var d = new Date(date);
// yyy-MM-dd
return [pad(d.getDate()),
pad(d.getMonth() + 1),
d.getFullYear()
].join('/') + " " +
pad(d.getHours()) + ":" +
pad(d.getMinutes());
}
// In this example the code returns the correct date
var activity = {};
activity.startDate = '2017-07-02T00:00:00-08:00';
var startDate = GetDateSchedulerFormatted(activity.startDate); //start date 07/02/2017 00:00 d/m/yyy
var newDate = new Date(startDate); // returns Tue Aug 01 2017 00:00:00 GMT-0700 (Pacific Daylight Time) also 1 day off
var endDate = GetDateSchedulerFormatted(new Date(newDate.setTime(newDate.getTime() + 30 * 86400000))); //returns correct date 01/08/2017 00: 00 d / m / yyyy
console.log('activity.startDate: ' + activity.startDate +
'\nstartDate : ' + startDate +
'\nnewDate : ' + GetDateSchedulerFormatted(newDate) +
'\nendDate : ' + endDate);
// In this next example it returns the date 1 year off
activity.startDate = '2016-12-12T00:00:00-08:00';
var startDate = GetDateSchedulerFormatted(activity.startDate); //returns 12/12/2016 00:00 d/m/yyy
var newDate = new Date(startDate); // returns Wed Jan 11 2017 00:00:00 GMT-0800 1 month ahead
var endDate = GetDateSchedulerFormatted(new Date(newDate.setTime(newDate.getTime() + 30 * 86400000))); //returns 11/01/2017 00:0 d/m/yyy
console.log('activity.startDate: ' + activity.startDate +
'\nstartDate : ' + startDate +
'\nnewDate : ' + GetDateSchedulerFormatted(newDate) +
'\nendDate : ' + endDate);
// In this example the same exact date is returned
activity.startDate = '2017-02-01T00:00:00-08:00';
var startDate = GetDateSchedulerFormatted(activity.startDate); //returns 01/02/2017 00:00 d/m/yyy
var newDate = new Date(startDate); // returns Wed Feb 01 2017 00:00:00 GMT-0800
var endDate = GetDateSchedulerFormatted(new Date(newDate.setTime(newDate.getTime() + 30 * 86400000))); //returns 01/02/2017 00:00 the same date, it 's not 30 days ahead
console.log('activity.startDate: ' + activity.startDate +
'\nstartDate : ' + startDate +
'\nnewDate : ' + GetDateSchedulerFormatted(newDate) +
'\nendDate : ' + endDate);
// Then in this final example I get NaN / NaN / NaN NaN: NaN
activity.startDate = '2017-02-25T00:00:00-08:00';
var startDate = GetDateSchedulerFormatted(activity.startDate); //returns 25/02/2017 00:00 d/m/yyy
var newDate = new Date(startDate); // returns invalid date
var endDate = GetDateSchedulerFormatted(new Date(newDate.setTime(newDate.getTime() + 30 * 86400000))); //returns NaN/NaN/NaN NaN:NaN
console.log('activity.startDate: ' + activity.startDate +
'\nstartDate : ' + startDate +
'\nnewDate : ' + GetDateSchedulerFormatted(newDate) +
'\nendDate : ' + endDate);
Thanks To Jordan S and zzzzBov for the help. I decided to go with moment.js
a code snippet of how I returned the correct dates
var startDate = moment(activity.startDate);
var endDate = moment(activity.startDate);
endDate = endDate.clone().add(1, 'months').calendar();
endDate = moment(endDate);
startDate = startDate._d;
endDate = endDate._d;
The moment() function returned the moment date object.
You have to .clone() the object to add to it correctly, also .calendar() returned a different format DD/MM/YYYY.
And finally the variable _d refered to the date object generated from the library.
I'm not that good at JS, so I have a problem with dates.
I want to set range for my DatePickers - that's why when the date is changed, I get it in the following format:
Wed Jul 08 2015 00:00:00 GMT+0200 (CEST)
I need to change it to the date in format dd/mm/yyyy to use the value later. Till now it looks like following:
var nowTemp = new Date();
$("#datepickerStart").on("changeDate", function (e) {
minDate = e.date;
console.log(minDate); // Wed Jul 08 2015 00:00:00 GMT+0200 (CEST)
// day = minDate.getDate(); <- doesn't work
// monthIndex = minDate.getMonth();
// year = minDate.getFullYear();
});
$('#datepickerStart').datepicker({
format: "dd/mm/yyyy",
startDate : new Date('01/01/2009'),
endDate : new Date()
});
$('#datepickerEnd').datepicker({
format: "dd/mm/yyyy",
startDate : minDate,//""+day+"/"+monthIndex+"/"+year,<- tried different approaches
endDate : new Date()
});
If I use minDate.format("dd/mm/yyyy"), it returns error "Uncaught TypeError: minDate.format is not a function".
Thanks in advance for help.
A good alternative for doing this is using momenjs library.
Other alternative is that you create a function which formats your date as follow:
var formatDate = function(d) {
var date = d.getDate();
var month = d.getMonth();
var year = d.getFullYear();
var newDate = (date < 10 ? ('0' + date) : date) + '/' + (month < 10 ? ('0' + month) : month) + '/' + year;
alert(newDate);
}
// Usage example
var now = new Date();
formatDate(now)
I am trying to format a date so I can use a compare function to sort the data
$(xml).find("item").each(function () {
var dateText = $(this).find("Date").text();
var year = dateText.substr(0,4);
var month = dateText.substr(4,2) ;
var day = dateText.substring(6,2);
var newDate = new Date(year, month, day);
When I display the newDate I get this: Mon Jul 03 2017 00:00:00 GMT-0700 (Pacific Daylight Time) which isn't close to the actual dates which are in 2013 and 2014. Does anyone have a suggestion as to formating this correctly? Thanks!
Something like this should work
var dateText = $(this).find("Date").text();
if( dateText && dateText.length===8){
var year = dateText.substr(0,4);
var month = dateText.substr(4,2) ;
var day = dateText.substring(6,2);
var newDate = new Date(year, month, day);
}else{
dateText='TBD';
newDate='TBD';
}