Daylight saving issues with get date function - javascript

I am having issues with day light savings, I have tried tons of diferent ways but not working. Our clients are global so I did not want to use any timezone stuff.
The idea is you give a date and amount of days and get back a date. the date input has to be "DD-MM-YYYY" as we get this from an other system.
this is the code
CallculateDateFromDays = function(startDate, days) {
var policy_start_date_array = startDate.split("-");
var policy_start_date = new Date(policy_start_date_array[2], policy_start_date_array[1]-1, policy_start_date_array[0]);
var epoch = Math.floor(policy_start_date.getTime()/1000);
var days_seconds = (days - 1) * 86400;
var total_seconds = epoch + days_seconds;
var end_date = new Date(total_seconds*1000);
var dateString = ("0" + (end_date.getDate())).slice(-2) + "-" + ("0" + (end_date.getMonth()+1)).slice(-2) + "-" + end_date.getFullYear();
alert(dateString + " " + epoch);
};
CallculateDateFromDays("27-10-2013",2);
this should return the 28-10-2013 but when I use the date "27-10-2013" it returns "27-10-2013", but any other date is fine. I have tried using UTC but still same result.
Any ideas
Thanks

Related

Is there an easier way to write this method?

Hello everybody reading this.
I have a method to get todays date with current time.
If the deadline value in database is null it will get current datetime and formats it to the right format. else it will just format the deadline.
But I was wondering if there is an easier way to do this?
formatDateTime(deadline){
var DateTime;
if(deadline == null){
var myDate = new Date();
var month = ('0' + (myDate.getMonth() + 1)).slice(-2);
var date = ('0' + myDate.getDate()).slice(-2);
var year = myDate.getFullYear();
var hour = ('0' + myDate.getHours()).slice(-2);
var minute = ('0' + myDate.getMinutes()).slice(-2);
var formattedDate = year + '-' + month + '-' + date + 'T' + hour + ':' + minute;
DateTime = moment(formattedDate, 'YYYY-MM-DD HH:mm').format('YYYY-MM-DDTHH:mm');
} else {
DateTime = moment(deadline, 'YYYY-MM-DD HH:mm').format('YYYY-MM-DDTHH:mm');
};
return DateTime;
}
As #Andrew said, You are already using moment
So this version will do exactly what your current function do
function formatDateTime(deadline){
if(deadline == null){
deadline = moment().format('YYYY-MM-DD HH:mm');
}
return moment(deadline, 'YYYY-MM-DD HH:mm').format('YYYY-MM-DDTHH:mm');
}
if you're using momentjs, you can just pass a Date object to the moment function. if the function receives no arguments, it will default to the current time (same as new Date()).
formatDateTime(deadline) {
return moment(deadline).format('YYYY-MM-DDTHH:mm');
}

Convert date object in dd/mm/yyyy hh:mm:ss format [duplicate]

This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 5 years ago.
I have a datetime object and its value is as follows
2017-03-16T17:46:53.677
Can someone please let me know how to convert this to dd/mm/yyyy hh:mm:ss format
I googled a lott and could not find format conversion for this particular input.
You can fully format the string as mentioned in other posts. But I think your better off using the locale functions in the date object?
var d = new Date("2017-03-16T17:46:53.677");
console.log( d.toLocaleString() );
edit :
ISO 8601 ( the format you are constructing with ) states the time zone is appended at the end with a [{+|-}hh][:mm] at the end of the string.
so you could do this :
var tzOffset = "+07:00"
var d = new Date("2017-03-16T17:46:53.677"+ tzOffset);
console.log(d.toLocaleString());
var d = new Date("2017-03-16T17:46:53.677"); // assumes local time.
console.log(d.toLocaleString());
var d = new Date("2017-03-16T17:46:53.677Z"); // UTC time
console.log(d.toLocaleString());
edit :
Just so you know the locale function displays the date and time in the manner of the users language and location. European date is dd/mm/yyyy and US is mm/dd/yyyy.
var d = new Date("2017-03-16T17:46:53.677");
console.log(d.toLocaleString("en-US"));
console.log(d.toLocaleString("en-GB"));
Here we go:
var today = new Date();
var day = today.getDate() + "";
var month = (today.getMonth() + 1) + "";
var year = today.getFullYear() + "";
var hour = today.getHours() + "";
var minutes = today.getMinutes() + "";
var seconds = today.getSeconds() + "";
day = checkZero(day);
month = checkZero(month);
year = checkZero(year);
hour = checkZero(hour);
minutes = checkZero(minutes);
seconds = checkZero(seconds);
console.log(day + "/" + month + "/" + year + " " + hour + ":" + minutes + ":" + seconds);
function checkZero(data){
if(data.length == 1){
data = "0" + data;
}
return data;
}

Get difference in months and list the months in an array between two dates in javascript

I'm having two dates given below with the format for which I need to get the number of months that are there in between them.I tried Difference in months between dates in Javascript :
but the format is not matching with the one that I have.Can anybody suggest a fix please?
startDate:"2015-09-07",
endDate: "2015-12-30"
Also I need to display the months that are there in between the dates like:
var months=["sept","oct","nov","dec","jan","feb"]
Well, you could always split string and use month like this:
var startDate = startDate.split("-");
var endDate= endDate.split("-");
var MonthDifference = endDate[1] - startDate[1];
So you could for example do this function:
function DifferenceInMonths(startDate, endDate){
startDate= startDate.split("-");
endDate= endDate.split("-");
return endDate[1] - startDate[1];
}
But then we are facing problem where these dates could happen in 2 different years. What if you would try this:
function differenceCalculatedInMonthsByUnix(startDate, endDate){
startDate = new Date(startDate).getTime();
endDate= new Date(endDate).getTime();
var difference = endDate - startDate;
return timeMe(difference);
}
function timeMe(unix_timestamp){
unix_timestamp = parseInt(unix_timestamp);
var date = new Date(unix_timestamp);
var days = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear()
// hours part from the timestamp
var hours = date.getHours();
// minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// seconds part from the timestamp
var seconds = "0" + date.getSeconds();
// will display time in 10:30:23 format
var formattedTime = days + '.' + month + '.' + year + ' at:' + hours + ':' + minutes.substr(minutes.length-2) + ':' + seconds.substr(seconds.length-2);
return (12 * year) + month
}
Not sure did i do that TimeMe() my self or did i find it from stackOverflow so if some one needs credits, pm me.
But yea the idea in this is, that we turn date into unix time stamp, calculate difference, and turn it into months.

The day of the month does not show up properly in javascript (html)

This is my javascript code:
function borrowbook ()
{
var today = new Date();
var day = today.getDate();
var month = today.getMonth()+1;
var year = today.getFullYear();
var input_day = document.getElementById("textbox").value;
var newday = today.setDate(day + input_day);
var fulltime1 = newday + "-" + month + "-" + year;
alert ("Return Date is: " + fulltime1);
}
And the result was not my expected result:
Actually what I want to do is if a user enters a value in 'Days allowed',I want to display the book return date.But I do not know why does the day of the month cannot show up properly.Any suggestion to solve this problem?
When you do:
var newday = today.setDate(day + input_day);
you are setting the value of newday to the return value of today.setDate(...), which is a time clip.
Since *input_day* is the value of a form control, and such values are always strings, the + operator will concatenate the values, not add them.
What you probably want is the date, so:
today.setDate(day + +input_day); // set the new date, converting input_date to Number
var newday = today.getDate(); // get the new date
Also, you should get the month and year after adding the day as it may change their values:
31 May + 1 day -> 1 June
There are three things you need to change.
Here is a working jsfiddle.
http://jsfiddle.net/bbankes/VMn3x/
First, the month and the year may also be incorrect. If today were 31-Dec 2014, your code would not show 10-Jan 2014, but instead 10-Dec 2013. You can rectify this by getting the day month and the year from the renew date instead of today's date.
Second, input_day is a string, so you need to parse it as an integer using the built-in javascript function parseInt();
Third, the setDate() method on a Date object does not return the new date. This is the problem that RobG shows.
The new function is as follows:
function borrowbook() {
var today = new Date();
var day = today.getDate();
var input_day = document.getElementById("textbox").value;
var returnDate = new Date();
returnDate.setDate(day + parseInt(input_day));
var returnDay = returnDate.getDate();
var returnMonth = returnDate.getMonth() + 1;
var returnYear = returnDate.getFullYear();
var fulltime1 = returnDay + "-" + returnMonth + "-" + returnYear;
alert ("Return Date is: " + fulltime1);
}

Javascript DateDiff

I am having a problem with the DateDiff function. I am trying to figure out the Difference between two dates/times. I have read this posting (What's the best way to calculate date difference in Javascript) and I also looked at this tutorial (http://www.javascriptkit.com/javatutors/datedifference.shtml) but I can't seem to get it.
Here is what I tried to get to work with no success. Could someone please tell me what I am doing and how I can simplify this. Seems a little over coded...?
//Set the two dates
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var currDate = month + "/" + day + "/" + year;
var iniremDate = "8/10/2012";
//Show the dates subtracted
document.write('DateDiff is: ' + currDate - iniremDate);
//Try this function...
function DateDiff(date1, date2) {
return date1.getTime() - date2.getTime();
}
//Print the results of DateDiff
document.write (DateDiff(iniremDate, currDate);
Okay for those who would like a working example here is a simple DateDiff ex that tells date diff by day in a negative value (date passed already) or positive (date is coming).
EDIT: I updated this script so it will do the leg work for you and convert the results in to in this case a -10 which means the date has passed. Input your own dates for currDate and iniPastedDate and you should be good to go!!
//Set the two dates
var currentTime = new Date()
var currDate = currentTime.getMonth() + 1 + "/" + currentTime.getDate() + "/" + currentTime.getFullYear() //Todays Date - implement your own date here.
var iniPastedDate = "8/7/2012" //PassedDate - Implement your own date here.
//currDate = 8/17/12 and iniPastedDate = 8/7/12
function DateDiff(date1, date2) {
var datediff = date1.getTime() - date2.getTime(); //store the getTime diff - or +
return (datediff / (24*60*60*1000)); //Convert values to -/+ days and return value
}
//Write out the returning value should be using this example equal -10 which means
//it has passed by ten days. If its positive the date is coming +10.
document.write (DateDiff(new Date(iniPastedDate),new Date(currDate))); //Print the results...
Your first try does addition first and then subtraction. You cannot subtract strings anyway, so that yields NaN.
The second trry has no closing ). Apart from that, you're calling getTime on strings. You'd need to use new Date(...).getTime(). Note that you get the result in milliseconds when subtracting dates. You could format that by taking out full days/hours/etc.
function setDateWeek(setDay){
var d = new Date();
d.setDate(d.getDate() - setDay); // <-- add this
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1;
var curr_year = d.getFullYear();
return curr_date + "-" + curr_month + "-" + curr_year;
}
setDateWeek(1);
No need to include JQuery or any other third party library.
Specify your input date format in title tag.
HTML:
< script type="text/javascript" src="http://services.iperfect.net/js/IP_generalLib.js">
Use javascript function:
IP_dateDiff(strDate1,strDate2,strDateFormat,debug[true/false])
alert(IP_dateDiff('11-12-2014','12-12-2014','DD-MM-YYYY',false));
IP_dateDiff function will return number of days.

Categories