i need to concatenate a date value and a time value to make one value representing a datetime in javascript.
thanks,
daniel
Working with strings is fun and all, but let's suppose you have two datetimes and don't like relying on strings.
function combineDateWithTime(d, t)
{
return new Date(
d.getFullYear(),
d.getMonth(),
d.getDate(),
t.getHours(),
t.getMinutes(),
t.getSeconds(),
t.getMilliseconds()
);
}
Test:
var taxDay = new Date(2016, 3, 15); // months are 0-indexed but years and dates aren't.
var clockout = new Date(0001, 0, 1, 17);
var timeToDoTaxes = combineDateWithTime(taxDay, clockout);
// yields: Fri Apr 15 2016 17:00:00 GMT-0700 (Pacific Daylight Time)
I could not make the accepted answer work so used moment.js
date = moment(selected_date + ' ' + selected_time, "YYYY-MM-DD HH:mm");
date._i "11-06-2014 13:30"
Assuming "date" is the date string and "time" is the time string:
// create Date object from valid string inputs
var datetime = new Date(date+' '+time);
// format the output
var month = datetime.getMonth()+1;
var day = datetime.getDate();
var year = datetime.getFullYear();
var hour = this.getHours();
if (hour < 10)
hour = "0"+hour;
var min = this.getMinutes();
if (min < 10)
min = "0"+min;
var sec = this.getSeconds();
if (sec < 10)
sec = "0"+sec;
// put it all togeter
var dateTimeString = month+'/'+day+'/'+year+' '+hour+':'+min+':'+sec;
Depending on the type of the original date and time value there are some different ways to approach this.
A Date object (which has both date and time) may be created in a number of ways.
birthday = new Date("December 17, 1995 03:24:00");
birthday = new Date(1995,11,17);
birthday = new Date(1995,11,17,3,24,0);
If the original date and time also is objects of type Date, you may use getHours(), getMinutes(), and so on to extract the desired values.
For more information, see Mozilla Developer Center for the Date object.
If you provide more detailed information in your question I may edit the answer to be more specific.
Related
Hi, I would like to add 12 months and subtract 1 day for my current
date.
Example :
valStartDate :2018-01-20
expected_date:2019-01-19
I try below code but error "getFullYear() not a function to allow"
this.endDate =this.valStartDate.getFullYear()+1+'-'+this.valStartDate.getMonth()+'-'+(this.valStartDate.getDate()-1);
Ensure that your given start date is a date and not a string.
var startDate = new Date(2018, 0, 20);
var startDatePlus12Months = new Date(startDate.setMonth(startDate.getMonth() + 12));
var expectedDate = new Date(startDatePlus12Months.getFullYear(), startDatePlus12Months.getMonth(), startDatePlus12Months.getDate() - 1);
Here is a method of abstracting the date you want, apply this the variable and you should be good to go.
var date = new Date(); // now
var newDate = new Date(date.getFullYear() + 1, date.getMonth(), date.getDate() - 1);
console.log(newDate.toLocaleDateString());
this.valStartDate.getFullYear() In order for this to work, this.valStartDate must be a valid javascript date and look the same format as new Date(); would give you.
Fri Apr 26 2019 11:52:15 GMT+0100 (British Summer Time)
this.endDate = new Date(this.endDate); // <= maybe you get a string date...
this.endDate.setMonth(this.endDate.getMonth() + 12);
this.endDate.setDate(this.endDate.getDate() - 1);
If you're getting your date from a server or from a previous Json format, maybe you need to convert it from string to Date first: this.endDate = new Date(this.endDate);. It seems this is your case.
This is easy with the help of Moment.js:
const startDate = moment('2018-01-20');
const endDate = startDate.add(12, 'months').subtract(1, 'days').toDate();
I am ploting a chart using google annotated timeline chart
https://code.google.com/apis/ajax/playground/?type=visualization#annotated_time_line
I am getting my data through ajax call in json format in an array like this
d[1][0] = 9/30/04, d[2][0] = 12/31/04
i have to loop through these values to add to data rows
for (m = 1; m < datavalues.length; m++) {
data.addRows('DATE', parseFloat(datavalues[m][2]), parseFloat(datavalues[m][3]), parseFloat(datavalues[m][4]), parseFloat(datavalues[m][5])]);
}
But code accepts format like
[new Date(2008, 1 ,1), 30000, null, null, 40645, null, null]
So how to change the format?
If you start with date in format 9/30/04, which seems something like mm/dd/yy, then all you need is to separate those values with split function
var inputDate = '9/30/04',
splitDate = inputDate.split('/'); // => ["9", "30", "04"]
After that, you need to prepare year, month and day numbers
var inputDate = '9/30/04',
splitDate = inputDate.split('/'),
year = parseInt(splitDate[2]) + (parseInt(splitDate[2]) < 50 ? 2000 : 1900), // careful with this, I don't know what years you are dealing with
month = parseInt(splitDate[0]),
day = parseInt(splitDate[1]);
And use them as parameters to create new Date object
var inputDate = '9/30/04',
splitDate = inputDate.split('/'),
year = parseInt(splitDate[2]) + (parseInt(splitDate[2]) < 50 ? 2000 : 1900),
month = parseInt(splitDate[0]),
day = parseInt(splitDate[1]),
date = new Date(year, month, day); // => Date {Sat Oct 30 2004 00:00:00 GMT+0300 (FLE Standard Time)}
You just need to make sure, that format remains the same mm/dd/yy. I would make some sort of date conversion function, that takes input date in specific format and returns date object.
Use this date object in your chart options.
var dateStart = $('input[id=orderdate-0]').val();
var timeStart = $('input[id=ordertime-0]').val();
var dateEnd = $('input[id=orderdate-1]').val();
var timeEnd = $('input[id=orderime-1]').val();
var startDate = new Date(dateStart + " " + timeStart);
var endDate = new Date(dateEnd + " " + timeEnd);
startDate.getTime();
alert(startDate);
i am trying to combine dateStart which is '2013-12-11' and timeStart which is '11:00' and trying to generate date out of it. But i get alert like invalid date. Is there anything wrong in code.?
The Date constructor is very particular about the date string formats it accepts.
Examples:
Dec 25, 1995
Wed, 09 Aug 1995 00:00:00
2011-10-10T14:48:00 (JavaScript 1.8.5+)
There is another constructor that take in the individual components of the date. If you break up your date strings into components you can use the following:
new Date(year, month, day, hour, minute);
Use moment JS plugin http://momentjs.com/
It's a date library for parsing, validating, manipulating, and formatting dates.
That is not a valid format for the parse function, you can use this instead:
var arr = dateStart.split('-');
var timeArr = timeStart.split(':');
new Date(arr[0], arr[1] -1, arr[2], timeArr[0] -1, timeArr[1] -1);
Read this.
Live DEMO
I am trying to calculate the time between two times on the current date using JavaScript. There are other questions similar to this one, but none seem to work, and few with many upvotes that I can find.
I have the following, which fails on the line: var diff = new Date(time1 - time2);, which always gives me an invalid Date when alerted, so it is clearly failing. I cannot work out why.
The initial date is added in the format of: hh:mm:ss in an input field. I am using jQuery.
$(function(){
$('#goTime').click(function(){
var currentDate = new Date();
var dateString = (strpad(currentDate.getDate()) +'-'+ strpad(currentDate.getMonth()+1)+'-'+currentDate.getFullYear()+' '+ $('#starttime').val());
var time1 = new Date(dateString).getTime();
var time2 = new Date().getTime();
var diff = new Date(time1 - time2);
var hours = diff.getHours();
var minutes = diff.getMinutes();
var seconds = diff.getMinutes();
alert(hours + ':' + minutes + ':' + seconds);
});
});
function strpad(val){
return (!isNaN(val) && val.toString().length==1)?"0"+val:val;
}
dateString is equal to: 14-01-2013 23:00
You have the fields in dateString backwards. Swap the year and day fields...
> new Date('14-01-2013 23:00')
Invalid Date
> new Date('2013-01-14 23:00')
Mon Jan 14 2013 23:00:00 GMT-0800 (PST)
dd-MM-yyyy HH:mm is not recognized as a valid time format by new Date(). You have a few options though:
Use slashes instead of dashes: dd/MM/yyyy HH:mm date strings are correctly parsed.
Use ISO date strings: yyyy-MM-dd HH:mm are also recognized.
Build the Date object yourself.
For the second option, since you only really care about the time, you could just split the time string yourself and pass them to Date.setHours(h, m, s):
var timeParts = $('#starttime').val().split(':', 2);
var time1 = new Date();
time1.setHours(timeParts[0], timeParts[1]);
You are experiencing an invalid time in your datestring. time1 is NaN, and so diff will be. It might be better to use this:
var date = new Date();
var match = /^(\d+):(\d+):(\d+)$/.exec($('#starttime').val()); // enforcing format
if (!match)
return alert("Invalid input!"); // abort
date.setHours(parseInt(match[1], 10));
date.setMinutes(parseInt(match[2], 10));
date.setSeconds(parseInt(match[3], 10));
var diff = Date.now() - date;
If you are trying to calculate the time difference between two dates, then you do not need to create a new date object to do that.
var time1 = new Date(dateString).getTime();
var time2 = new Date().getTime();
var diff = time1 - time2;// number of milliseconds
var seconds = diff/1000;
var minutes = seconds/60;
var hours = minutes/60;
Edit: You will want to take into account broofa's answer as well to
make sure your date string is correctly formatted
The getTime function returns the number of milliseconds since Jan 1, 1970. So by subtracting the two values you are left with the number of milliseconds between each date object. If you were to pass that value into the Date constructor, the resulting date object would not be what you are expecting. see getTime
I have a current Date object that needs to be incremented by one day using the JavaScript Date object. I have the following code in place:
var ds = stringFormat("{day} {date} {month} {year}", {
day: companyname.i18n.translate("day", language)[date.getUTCDay()],
date: date.getUTCDate(),
month: companyname.i18n.translate("month", language)[date.getUTCMonth()],
year: date.getUTCFullYear()
});
How can I add one day to it?
I've added +1 to getUTCDay() and getUTCDate() but it doesn't display 'Sunday'
for day, which I am expecting to happen.
To add one day to a date object:
var date = new Date();
// add a day
date.setDate(date.getDate() + 1);
In my humble opinion the best way is to just add a full day in milliseconds, depending on how you factor your code it can mess up if you are on the last day of the month.
For example Feb 28 or march 31.
Here is an example of how I would do it:
var current = new Date(); //'Mar 11 2015' current.getTime() = 1426060964567
var followingDay = new Date(current.getTime() + 86400000); // + 1 day in ms
followingDay.toLocaleDateString();
Imho this insures accuracy
Here is another example. I do not like that. It can work for you but not as clean as example above.
var today = new Date('12/31/2015');
var tomorrow = new Date(today);
tomorrow.setDate(today.getDate()+1);
tomorrow.toLocaleDateString();
Imho this === 'POOP'
So some of you have had gripes about my millisecond approach because of day light savings time. So I'm going to bash this out. First, Some countries and states do not have Day light savings time. Second Adding exactly 24 hours is a full day. If the date number does not change once a year but then gets fixed 6 months later I don't see a problem there. But for the purpose of being definite and having to deal with allot the evil Date() I have thought this through and now thoroughly hate Date. So this is my new Approach.
var dd = new Date(); // or any date and time you care about
var dateArray = dd.toISOString().split('T')[0].split('-').concat( dd.toISOString().split('T')[1].split(':') );
// ["2016", "07", "04", "00", "17", "58.849Z"] at Z
Now for the fun part!
var date = {
day: dateArray[2],
month: dateArray[1],
year: dateArray[0],
hour: dateArray[3],
minutes: dateArray[4],
seconds:dateArray[5].split('.')[0],
milliseconds: dateArray[5].split('.')[1].replace('Z','')
}
Now we have our Official Valid international Date Object clearly written out at Zulu meridian.
Now to change the date
dd.setDate(dd.getDate()+1); // this gives you one full calendar date forward
tomorrow.setDate(dd.getTime() + 86400000);// this gives your 24 hours into the future. do what you want with it.
If you want add a day (24 hours) to current datetime you can add milliseconds like this:
new Date(Date.now() + ( 3600 * 1000 * 24))
int days = 1;
var newDate = new Date(Date.now() + days*24*60*60*1000);
CodePen
var days = 2;
var newDate = new Date(Date.now()+days*24*60*60*1000);
document.write('Today: <em>');
document.write(new Date());
document.write('</em><br/> New: <strong>');
document.write(newDate);
Inspired by jpmottin in this question, here's the one line code:
var dateStr = '2019-01-01';
var days = 1;
var result = new Date(new Date(dateStr).setDate(new Date(dateStr).getDate() + days));
document.write('Date: ', result); // Wed Jan 02 2019 09:00:00 GMT+0900 (Japan Standard Time)
document.write('<br />');
document.write('Trimmed Date: ', result.toISOString().substr(0, 10)); // 2019-01-02
Hope this helps
simply you can do this
var date = new Date();
date.setDate(date.getDate() + 1);
console.log(date);
now the date will be the date of tomorrow. here you can add or deduct the number of days as you wish.
This is function you can use to add a given day to a current date in javascript.
function addDayToCurrentDate(days){
let currentDate = new Date()
return new Date(currentDate.setDate(currentDate.getDate() + days))
}
// current date = Sun Oct 02 2021 13:07:46 GMT+0200 (South Africa Standard Time)
// days = 2
console.log(addDayToCurrentDate(2))
// Mon Oct 04 2021 13:08:18 GMT+0200 (South Africa Standard Time)
// Function gets date and count days to add to passed date
function addDays(dateTime, count_days = 0){
return new Date(new Date(dateTime).setDate(dateTime.getDate() + count_days));
}
// Create some date
const today = new Date("2022-02-19T00:00:00Z");
// Add some days to date
const tomorrow = addDays(today, 1);
// Result
console.log("Tomorrow => ", new Date(tomorrow).toISOString());
// 2022-02-20T00:00:00.000Z
We can get date of the day after today by using timedelta with numOfDays specified as 1 below.
from datetime import date, timedelta
tomorrow = date.today() + timedelta(days=1)
currentDay = '2019-12-06';
currentDay = new Date(currentDay).add(Date.DAY, +1).format('Y-m-d');