How to convert string to Time with javascript [duplicate] - javascript

Please see the below code;
var d = new Date();
var s = "01.00 AM";
d.setTime(s);
I know this code is wrong. Please give me the correct way to set the time. I have 12 hour time in string format in my hand.
The time will vary. Cannot know what will be the time earlier. Also it is 12 hour time. So it will be AM or PM

You can parse the time with a regex, and set the hours and minutes accordingly:
http://jsfiddle.net/54VkC/1/
var d = new Date(),
s = "01.25 PM",
parts = s.match(/(\d+)\.(\d+) (\w+)/),
hours = /am/i.test(parts[3]) ? parseInt(parts[1], 10) : parseInt(parts[1], 10) + 12,
minutes = parseInt(parts[2], 10);
d.setHours(hours);
d.setMinutes(minutes);
alert(d);
Edit 1:
As jaisonDavis pointed out, the original code will not work for AM or PM for 12.XX, which was an oversight since I never use 12-hour format myself, thinking it started at 00.00 which was wrong.
The corrected code which handles these cases can be seen here:
http://jsfiddle.net/54VkC/93/
var test, parts, hours, minutes, date,
d = (new Date()).getTime(),
tests = ['01.25 PM', '11.35 PM', '12.45 PM', '01.25 AM', '11.35 AM', '12.45 AM'],
i = tests.length,
timeReg = /(\d+)\.(\d+) (\w+)/;
for(; i-- > 0;) {
test = tests[i];
parts = test.match(timeReg);
hours = /am/i.test(parts[3]) ?
function(am) {return am < 12 ? am : 0}(parseInt(parts[1], 10)) :
function(pm) {return pm < 12 ? pm + 12 : 12}(parseInt(parts[1], 10));
minutes = parseInt(parts[2], 10);
date = new Date(d);
date.setHours(hours);
date.setMinutes(minutes);
console.log(test + ' => ' + date);
}

I'm late to the party, but I thought I'd share a funtion that doesn't use regex:
function setDateTime(date, time) {
var index = time.indexOf("."); // replace with ":" for differently displayed time.
var index2 = time.indexOf(" ");
var hours = time.substring(0, index);
var minutes = time.substring(index + 1, index2);
var mer = time.substring(index2 + 1, time.length);
if (mer == "PM"){
hours = hours + 12;
}
date.setHours(hours);
date.setMinutes(minutes);
date.setSeconds("00");
return date;
}

Using moment.js will be the easy solution.
const fullDate = new Date();
// fullDate = Tue Dec 12 2017 11:18:30 GMT+0530 (IST) {}
const time = '01.00 AM';
const d = moment(fullDate).format('L'); // d = "12/12/2017"
const date = moment(d +' '+ time).format();
// date = "2017-12-12T01:00:00+05:30"
If you want convert moment date to js date
const jsDate = moment(date).toDate();

function getCurrentDate() {
var lDate = new Date();
var lDay = lDate.getDate();
var lMonth = lDate.getMonth() + 1;
var lYear = lDate.getFullYear();
if (lDay < 10) {
lDay = '0' + lDay
}
if (lMonth < 10) {
lMonth = '0' + lMonth
}
mCurrentDate = lYear + "-" + lMonth + "-" + lDay + "T00:00:00+05:30";
}

I added a few things as an improvement to the accepted answer by #thebreiflabb to suit my use case and thought i'd share.
if the regex is changed to timeReg = /(\d+)[\.|:](\d+)\s?(\w+)/;,
it'll handle a few other common cases.
namely:
using a colon instead of decimal point between hours and minutes
allowing am/pm to immediately follow the time with no space
also, setting the seconds to 0 (since that was my main use case)
the resulting code would be:
var test, parts, hours, minutes, date,
d = (new Date()).getTime(),
tests = ['01.25 PM', '01:25pm', '1:25 PM', '11.35 PM', '12.45 PM', '01.25 AM', '11.35 AM', '12.45 AM'],
i = tests.length,
timeReg = /(\d+)[\.|:](\d+)\s?(\w+)/;
for(; i-- > 0;) {
test = tests[i];
parts = test.match(timeReg);
hours = /am/i.test(parts[3]) ?
function(am) {return am < 12 ? am : 0}(parseInt(parts[1], 10)) :
function(pm) {return pm < 12 ? pm + 12 : 12}(parseInt(parts[1], 10));
minutes = parseInt(parts[2], 10);
date = new Date(d);
date.setHours(hours);
date.setMinutes(minutes);
date.setSeconds(0);
console.log(test + ' => ' + date);
}

Related

How to achieve the correct date output in my code?

I'm not including the 12:00 PM - 01:00 PM Time
For example:
8:00 AM - 5:00 PM = 8.00
If I input
8:00 AM - 10:00 PM = 2.00
But the correct output is supposed to be (13.00)
Here is my code:
_formatTime = function(amPmString) {
var d = new Date("03/04/2019 " + amPmString);
return d.getHours() + ':' + d.getMinutes();
}
_getTimeDifference = function(startTime, endTime) {
var start = moment.utc(startTime, "HH:mm");
var end = moment.utc(endTime, "HH:mm");
var t = (end.isBefore(start)) ? end.add(1, 'day') : '';
var diff = (end.diff(start)) / 3600000;
return (t) ? diff - 13 : diff;
};
The correct result that I want is that I have to total the hours of the time-in and time-out and disregard only the lunch break which is 1 hour (12pm-1pm) in the computation of total hours. If the time range that I put is not in the lunch break. It will not deduct 1 hours.
Try this:
_getTimeDifference = function(startTime, endTime) {
var start = moment(startTime, "HH:mm A");
var end = moment(endTime, "HH:mm A");
var t = (end.isBefore(start)) ? end : '';
var diff = (end.diff(start)) / 3600000 -1;
return (t) ? diff - 13 : diff;
};
If your datetime present in Am-Pm format :the TimeSpan class in Datejs might help simplify the problem. It could be exactly your answer, if your problem is just subtract to time in AM-Pm format
I suggest such a code
var date1= Date.parse("6:30 am");
var date2= Date.parse("11:00 pm");
var diff = new TimeSpan(date2- date1);
console.log("Hours: ", diff.hours);
console.log("Minutes: ", diff.minutes);
Solution without Moment.js:
// dt1 and dt2 are assumed to be Date() objects:
function hoursDiff( dt1, dt2 ) {
// Difference in hours:
var diff = Math.abs(Math.round( (dt2.getTime() - dt1.getTime()) / 1000 / (60 * 60) ) );
// If range overlaps 12:00 - 1:00 pm, subtract 1 hour:
if (dt1.getHours() <= 12 && dt2.getHours() >= 13) {
diff--
}
return diff;
}
console.log( hoursDiff( new Date('2020-08-12 8:00:00'), new Date('2020-08-12 17:00:00') ) ) // 8am-5pm = 8
console.log( hoursDiff( new Date('2020-08-12 8:00:00'), new Date('2020-08-12 22:00:00') ) ) // 8am-10pm = 13
This doesn't account for times that begin or end within the 12:00 - 1:00 pm range, just dates that overlap it completely or not at all. It also assumes dates begin and end on hour boundaries, i.e. doesn't account for fractional hours.

javascript adding 86400000ms to increment dates issue [duplicate]

I need to increment a date value by one day in JavaScript.
For example, I have a date value 2010-09-11 and I need to store the date of the next day in a JavaScript variable.
How can I increment a date by a day?
Three options for you:
1. Using just JavaScript's Date object (no libraries):
My previous answer for #1 was wrong (it added 24 hours, failing to account for transitions to and from daylight saving time; Clever Human pointed out that it would fail with November 7, 2010 in the Eastern timezone). Instead, Jigar's answer is the correct way to do this without a library:
// To do it in local time
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
// To do it in UTC
var tomorrow = new Date();
tomorrow.setUTCDate(tomorrow.getUTCDate() + 1);
This works even for the last day of a month (or year), because the JavaScript date object is smart about rollover:
// (local time)
var lastDayOf2015 = new Date(2015, 11, 31);
console.log("Last day of 2015: " + lastDayOf2015.toISOString());
var nextDay = new Date(+lastDayOf2015);
var dateValue = nextDay.getDate() + 1;
console.log("Setting the 'date' part to " + dateValue);
nextDay.setDate(dateValue);
console.log("Resulting date: " + nextDay.toISOString());
2. Using MomentJS:
var today = moment();
var tomorrow = moment(today).add(1, 'days');
(Beware that add modifies the instance you call it on, rather than returning a new instance, so today.add(1, 'days') would modify today. That's why we start with a cloning op on var tomorrow = ....)
3. Using DateJS, but it hasn't been updated in a long time:
var today = new Date(); // Or Date.today()
var tomorrow = today.add(1).day();
var myDate = new Date();
//add a day to the date
myDate.setDate(myDate.getDate() + 1);
The easiest way is to convert to milliseconds and add 1000*60*60*24 milliseconds e.g.:
var tomorrow = new Date(today.getTime()+1000*60*60*24);
Tomorrow in one line in pure JS but it's ugly !
new Date(new Date().setDate(new Date().getDate() + 1))
Here is the result :
Thu Oct 12 2017 08:53:30 GMT+0200 (Romance Summer Time)
None of the examples in this answer seem to work with Daylight Saving Time adjustment days. On those days, the number of hours in a day are not 24 (they are 23 or 25, depending on if you are "springing forward" or "falling back".)
The below AddDays javascript function accounts for daylight saving time:
function addDays(date, amount) {
var tzOff = date.getTimezoneOffset() * 60 * 1000,
t = date.getTime(),
d = new Date(),
tzOff2;
t += (1000 * 60 * 60 * 24) * amount;
d.setTime(t);
tzOff2 = d.getTimezoneOffset() * 60 * 1000;
if (tzOff != tzOff2) {
var diff = tzOff2 - tzOff;
t += diff;
d.setTime(t);
}
return d;
}
Here are the tests I used to test the function:
var d = new Date(2010,10,7);
var d2 = AddDays(d, 1);
document.write(d.toString() + "<br />" + d2.toString());
d = new Date(2010,10,8);
d2 = AddDays(d, -1)
document.write("<hr /><br />" + d.toString() + "<br />" + d2.toString());
d = new Date('Sun Mar 27 2011 01:59:00 GMT+0100 (CET)');
d2 = AddDays(d, 1)
document.write("<hr /><br />" + d.toString() + "<br />" + d2.toString());
d = new Date('Sun Mar 28 2011 01:59:00 GMT+0100 (CET)');
d2 = AddDays(d, -1)
document.write("<hr /><br />" + d.toString() + "<br />" + d2.toString());
You first need to parse your string before following the other people's suggestion:
var dateString = "2010-09-11";
var myDate = new Date(dateString);
//add a day to the date
myDate.setDate(myDate.getDate() + 1);
If you want it back in the same format again you will have to do that "manually":
var y = myDate.getFullYear(),
m = myDate.getMonth() + 1, // january is month 0 in javascript
d = myDate.getDate();
var pad = function(val) { var str = val.toString(); return (str.length < 2) ? "0" + str : str};
dateString = [y, pad(m), pad(d)].join("-");
But I suggest getting Date.js as mentioned in other replies, that will help you alot.
I feel that nothing is safer than .getTime() and .setTime(), so this should be the best, and performant as well.
const d = new Date()
console.log(d.setTime(d.getTime() + 1000 * 60 * 60 * 24)) // MILLISECONDS
.setDate() for invalid Date (like 31 + 1) is too dangerous, and it depends on the browser implementation.
Getting the next 5 days:
var date = new Date(),
d = date.getDate(),
m = date.getMonth(),
y = date.getFullYear();
for(i=0; i < 5; i++){
var curdate = new Date(y, m, d+i)
console.log(curdate)
}
Two methods:
1:
var a = new Date()
// no_of_days is an integer value
var b = new Date(a.setTime(a.getTime() + no_of_days * 86400000)
2: Similar to the previous method
var a = new Date()
// no_of_days is an integer value
var b = new Date(a.setDate(a.getDate() + no_of_days)
Via native JS, to add one day you may do following:
let date = new Date(); // today
date.setDate(date.getDate() + 1) // tomorrow
Another option is to use moment library:
const date = moment().add(14, "days").toDate()
Get the string value of the date using the dateObj.toJSON() method Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON
Slice the date from the returned value and then increment by the number of days you want.
var currentdate = new Date();
currentdate.setDate(currentdate.getDate() + 1);
var tomorrow = currentdate.toJSON().slice(0,10);
Date.prototype.AddDays = function (days) {
days = parseInt(days, 10);
return new Date(this.valueOf() + 1000 * 60 * 60 * 24 * days);
}
Example
var dt = new Date();
console.log(dt.AddDays(-30));
console.log(dt.AddDays(-10));
console.log(dt.AddDays(-1));
console.log(dt.AddDays(0));
console.log(dt.AddDays(1));
console.log(dt.AddDays(10));
console.log(dt.AddDays(30));
Result
2017-09-03T15:01:37.213Z
2017-09-23T15:01:37.213Z
2017-10-02T15:01:37.213Z
2017-10-03T15:01:37.213Z
2017-10-04T15:01:37.213Z
2017-10-13T15:01:37.213Z
2017-11-02T15:01:37.213Z
Not entirelly sure if it is a BUG(Tested Firefox 32.0.3 and Chrome 38.0.2125.101), but the following code will fail on Brazil (-3 GMT):
Date.prototype.shiftDays = function(days){
days = parseInt(days, 10);
this.setDate(this.getDate() + days);
return this;
}
$date = new Date(2014, 9, 16,0,1,1);
$date.shiftDays(1);
console.log($date+"");
$date.shiftDays(1);
console.log($date+"");
$date.shiftDays(1);
console.log($date+"");
$date.shiftDays(1);
console.log($date+"");
Result:
Fri Oct 17 2014 00:01:01 GMT-0300
Sat Oct 18 2014 00:01:01 GMT-0300
Sat Oct 18 2014 23:01:01 GMT-0300
Sun Oct 19 2014 23:01:01 GMT-0200
Adding one Hour to the date, will make it work perfectly (but does not solve the problem).
$date = new Date(2014, 9, 16,0,1,1);
Result:
Fri Oct 17 2014 01:01:01 GMT-0300
Sat Oct 18 2014 01:01:01 GMT-0300
Sun Oct 19 2014 01:01:01 GMT-0200
Mon Oct 20 2014 01:01:01 GMT-0200
Results in a string representation of tomorrow's date. Use new Date() to get today's date, adding one day using Date.getDate() and Date.setDate(), and converting the Date object to a string.
const tomorrow = () => {
let t = new Date();
t.setDate(t.getDate() + 1);
return `${t.getFullYear()}-${String(t.getMonth() + 1).padStart(2, '0')}-${String(
t.getDate()
).padStart(2, '0')}`;
};
tomorrow();
Incrementing date's year with vanilla js:
start_date_value = "01/01/2019"
var next_year = new Date(start_date_value);
next_year.setYear(next_year.getYear() + 1);
console.log(next_year.getYear()); //=> 2020
Just in case someone wants to increment other value than the date (day)
Timezone/daylight savings aware date increment for JavaScript dates:
function nextDay(date) {
const sign = v => (v < 0 ? -1 : +1);
const result = new Date(date.getTime());
result.setDate(result.getDate() + 1);
const offset = result.getTimezoneOffset();
return new Date(result.getTime() + sign(offset) * offset * 60 * 1000);
}
This a simpler method ,
and it will return the date in simple yyyy-mm-dd format , Here it is
function incDay(date, n) {
var fudate = new Date(new Date(date).setDate(new Date(date).getDate() + n));
fudate = fudate.getFullYear() + '-' + (fudate.getMonth() + 1) + '-' + fudate.toDateString().substring(8, 10);
return fudate;
}
example :
var tomorrow = incDay(new Date(), 1); // the next day of today , aka tomorrow :) .
var spicaldate = incDay("2020-11-12", 1); // return "2020-11-13" .
var somedate = incDay("2020-10-28", 5); // return "2020-11-02" .
Note
incDay(new Date("2020-11-12"), 1);
incDay("2020-11-12", 1);
will return the same result .
Use this function, it´s solved my problem:
let nextDate = (daysAhead:number) => {
const today = new Date().toLocaleDateString().split('/')
const invalidDate = new Date(`${today[2]}/${today[1]}/${Number(today[0])+daysAhead}`)
if(Number(today[1]) === Number(12)){
return new Date(`${Number(today[2])+1}/${1}/${1}`)
}
if(String(invalidDate) === 'Invalid Date'){
return new Date(`${today[2]}/${Number(today[1])+1}/${1}`)
}
return new Date(`${today[2]}/${Number(today[1])}/${Number(today[0])+daysAhead}`)
}
Assigning the Increment of current date to other Variable
let startDate=new Date();
let endDate=new Date();
endDate.setDate(startDate.getDate() + 1)
console.log(startDate,endDate)

EDT/ EST issues while incrementing date in Javascript [duplicate]

I need to increment a date value by one day in JavaScript.
For example, I have a date value 2010-09-11 and I need to store the date of the next day in a JavaScript variable.
How can I increment a date by a day?
Three options for you:
1. Using just JavaScript's Date object (no libraries):
My previous answer for #1 was wrong (it added 24 hours, failing to account for transitions to and from daylight saving time; Clever Human pointed out that it would fail with November 7, 2010 in the Eastern timezone). Instead, Jigar's answer is the correct way to do this without a library:
// To do it in local time
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
// To do it in UTC
var tomorrow = new Date();
tomorrow.setUTCDate(tomorrow.getUTCDate() + 1);
This works even for the last day of a month (or year), because the JavaScript date object is smart about rollover:
// (local time)
var lastDayOf2015 = new Date(2015, 11, 31);
console.log("Last day of 2015: " + lastDayOf2015.toISOString());
var nextDay = new Date(+lastDayOf2015);
var dateValue = nextDay.getDate() + 1;
console.log("Setting the 'date' part to " + dateValue);
nextDay.setDate(dateValue);
console.log("Resulting date: " + nextDay.toISOString());
2. Using MomentJS:
var today = moment();
var tomorrow = moment(today).add(1, 'days');
(Beware that add modifies the instance you call it on, rather than returning a new instance, so today.add(1, 'days') would modify today. That's why we start with a cloning op on var tomorrow = ....)
3. Using DateJS, but it hasn't been updated in a long time:
var today = new Date(); // Or Date.today()
var tomorrow = today.add(1).day();
var myDate = new Date();
//add a day to the date
myDate.setDate(myDate.getDate() + 1);
The easiest way is to convert to milliseconds and add 1000*60*60*24 milliseconds e.g.:
var tomorrow = new Date(today.getTime()+1000*60*60*24);
Tomorrow in one line in pure JS but it's ugly !
new Date(new Date().setDate(new Date().getDate() + 1))
Here is the result :
Thu Oct 12 2017 08:53:30 GMT+0200 (Romance Summer Time)
None of the examples in this answer seem to work with Daylight Saving Time adjustment days. On those days, the number of hours in a day are not 24 (they are 23 or 25, depending on if you are "springing forward" or "falling back".)
The below AddDays javascript function accounts for daylight saving time:
function addDays(date, amount) {
var tzOff = date.getTimezoneOffset() * 60 * 1000,
t = date.getTime(),
d = new Date(),
tzOff2;
t += (1000 * 60 * 60 * 24) * amount;
d.setTime(t);
tzOff2 = d.getTimezoneOffset() * 60 * 1000;
if (tzOff != tzOff2) {
var diff = tzOff2 - tzOff;
t += diff;
d.setTime(t);
}
return d;
}
Here are the tests I used to test the function:
var d = new Date(2010,10,7);
var d2 = AddDays(d, 1);
document.write(d.toString() + "<br />" + d2.toString());
d = new Date(2010,10,8);
d2 = AddDays(d, -1)
document.write("<hr /><br />" + d.toString() + "<br />" + d2.toString());
d = new Date('Sun Mar 27 2011 01:59:00 GMT+0100 (CET)');
d2 = AddDays(d, 1)
document.write("<hr /><br />" + d.toString() + "<br />" + d2.toString());
d = new Date('Sun Mar 28 2011 01:59:00 GMT+0100 (CET)');
d2 = AddDays(d, -1)
document.write("<hr /><br />" + d.toString() + "<br />" + d2.toString());
You first need to parse your string before following the other people's suggestion:
var dateString = "2010-09-11";
var myDate = new Date(dateString);
//add a day to the date
myDate.setDate(myDate.getDate() + 1);
If you want it back in the same format again you will have to do that "manually":
var y = myDate.getFullYear(),
m = myDate.getMonth() + 1, // january is month 0 in javascript
d = myDate.getDate();
var pad = function(val) { var str = val.toString(); return (str.length < 2) ? "0" + str : str};
dateString = [y, pad(m), pad(d)].join("-");
But I suggest getting Date.js as mentioned in other replies, that will help you alot.
I feel that nothing is safer than .getTime() and .setTime(), so this should be the best, and performant as well.
const d = new Date()
console.log(d.setTime(d.getTime() + 1000 * 60 * 60 * 24)) // MILLISECONDS
.setDate() for invalid Date (like 31 + 1) is too dangerous, and it depends on the browser implementation.
Getting the next 5 days:
var date = new Date(),
d = date.getDate(),
m = date.getMonth(),
y = date.getFullYear();
for(i=0; i < 5; i++){
var curdate = new Date(y, m, d+i)
console.log(curdate)
}
Two methods:
1:
var a = new Date()
// no_of_days is an integer value
var b = new Date(a.setTime(a.getTime() + no_of_days * 86400000)
2: Similar to the previous method
var a = new Date()
// no_of_days is an integer value
var b = new Date(a.setDate(a.getDate() + no_of_days)
Via native JS, to add one day you may do following:
let date = new Date(); // today
date.setDate(date.getDate() + 1) // tomorrow
Another option is to use moment library:
const date = moment().add(14, "days").toDate()
Get the string value of the date using the dateObj.toJSON() method Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON
Slice the date from the returned value and then increment by the number of days you want.
var currentdate = new Date();
currentdate.setDate(currentdate.getDate() + 1);
var tomorrow = currentdate.toJSON().slice(0,10);
Date.prototype.AddDays = function (days) {
days = parseInt(days, 10);
return new Date(this.valueOf() + 1000 * 60 * 60 * 24 * days);
}
Example
var dt = new Date();
console.log(dt.AddDays(-30));
console.log(dt.AddDays(-10));
console.log(dt.AddDays(-1));
console.log(dt.AddDays(0));
console.log(dt.AddDays(1));
console.log(dt.AddDays(10));
console.log(dt.AddDays(30));
Result
2017-09-03T15:01:37.213Z
2017-09-23T15:01:37.213Z
2017-10-02T15:01:37.213Z
2017-10-03T15:01:37.213Z
2017-10-04T15:01:37.213Z
2017-10-13T15:01:37.213Z
2017-11-02T15:01:37.213Z
Not entirelly sure if it is a BUG(Tested Firefox 32.0.3 and Chrome 38.0.2125.101), but the following code will fail on Brazil (-3 GMT):
Date.prototype.shiftDays = function(days){
days = parseInt(days, 10);
this.setDate(this.getDate() + days);
return this;
}
$date = new Date(2014, 9, 16,0,1,1);
$date.shiftDays(1);
console.log($date+"");
$date.shiftDays(1);
console.log($date+"");
$date.shiftDays(1);
console.log($date+"");
$date.shiftDays(1);
console.log($date+"");
Result:
Fri Oct 17 2014 00:01:01 GMT-0300
Sat Oct 18 2014 00:01:01 GMT-0300
Sat Oct 18 2014 23:01:01 GMT-0300
Sun Oct 19 2014 23:01:01 GMT-0200
Adding one Hour to the date, will make it work perfectly (but does not solve the problem).
$date = new Date(2014, 9, 16,0,1,1);
Result:
Fri Oct 17 2014 01:01:01 GMT-0300
Sat Oct 18 2014 01:01:01 GMT-0300
Sun Oct 19 2014 01:01:01 GMT-0200
Mon Oct 20 2014 01:01:01 GMT-0200
Results in a string representation of tomorrow's date. Use new Date() to get today's date, adding one day using Date.getDate() and Date.setDate(), and converting the Date object to a string.
const tomorrow = () => {
let t = new Date();
t.setDate(t.getDate() + 1);
return `${t.getFullYear()}-${String(t.getMonth() + 1).padStart(2, '0')}-${String(
t.getDate()
).padStart(2, '0')}`;
};
tomorrow();
Incrementing date's year with vanilla js:
start_date_value = "01/01/2019"
var next_year = new Date(start_date_value);
next_year.setYear(next_year.getYear() + 1);
console.log(next_year.getYear()); //=> 2020
Just in case someone wants to increment other value than the date (day)
Timezone/daylight savings aware date increment for JavaScript dates:
function nextDay(date) {
const sign = v => (v < 0 ? -1 : +1);
const result = new Date(date.getTime());
result.setDate(result.getDate() + 1);
const offset = result.getTimezoneOffset();
return new Date(result.getTime() + sign(offset) * offset * 60 * 1000);
}
This a simpler method ,
and it will return the date in simple yyyy-mm-dd format , Here it is
function incDay(date, n) {
var fudate = new Date(new Date(date).setDate(new Date(date).getDate() + n));
fudate = fudate.getFullYear() + '-' + (fudate.getMonth() + 1) + '-' + fudate.toDateString().substring(8, 10);
return fudate;
}
example :
var tomorrow = incDay(new Date(), 1); // the next day of today , aka tomorrow :) .
var spicaldate = incDay("2020-11-12", 1); // return "2020-11-13" .
var somedate = incDay("2020-10-28", 5); // return "2020-11-02" .
Note
incDay(new Date("2020-11-12"), 1);
incDay("2020-11-12", 1);
will return the same result .
Use this function, it´s solved my problem:
let nextDate = (daysAhead:number) => {
const today = new Date().toLocaleDateString().split('/')
const invalidDate = new Date(`${today[2]}/${today[1]}/${Number(today[0])+daysAhead}`)
if(Number(today[1]) === Number(12)){
return new Date(`${Number(today[2])+1}/${1}/${1}`)
}
if(String(invalidDate) === 'Invalid Date'){
return new Date(`${today[2]}/${Number(today[1])+1}/${1}`)
}
return new Date(`${today[2]}/${Number(today[1])}/${Number(today[0])+daysAhead}`)
}
Assigning the Increment of current date to other Variable
let startDate=new Date();
let endDate=new Date();
endDate.setDate(startDate.getDate() + 1)
console.log(startDate,endDate)

Javascript set time string to date object

Please see the below code;
var d = new Date();
var s = "01.00 AM";
d.setTime(s);
I know this code is wrong. Please give me the correct way to set the time. I have 12 hour time in string format in my hand.
The time will vary. Cannot know what will be the time earlier. Also it is 12 hour time. So it will be AM or PM
You can parse the time with a regex, and set the hours and minutes accordingly:
http://jsfiddle.net/54VkC/1/
var d = new Date(),
s = "01.25 PM",
parts = s.match(/(\d+)\.(\d+) (\w+)/),
hours = /am/i.test(parts[3]) ? parseInt(parts[1], 10) : parseInt(parts[1], 10) + 12,
minutes = parseInt(parts[2], 10);
d.setHours(hours);
d.setMinutes(minutes);
alert(d);
Edit 1:
As jaisonDavis pointed out, the original code will not work for AM or PM for 12.XX, which was an oversight since I never use 12-hour format myself, thinking it started at 00.00 which was wrong.
The corrected code which handles these cases can be seen here:
http://jsfiddle.net/54VkC/93/
var test, parts, hours, minutes, date,
d = (new Date()).getTime(),
tests = ['01.25 PM', '11.35 PM', '12.45 PM', '01.25 AM', '11.35 AM', '12.45 AM'],
i = tests.length,
timeReg = /(\d+)\.(\d+) (\w+)/;
for(; i-- > 0;) {
test = tests[i];
parts = test.match(timeReg);
hours = /am/i.test(parts[3]) ?
function(am) {return am < 12 ? am : 0}(parseInt(parts[1], 10)) :
function(pm) {return pm < 12 ? pm + 12 : 12}(parseInt(parts[1], 10));
minutes = parseInt(parts[2], 10);
date = new Date(d);
date.setHours(hours);
date.setMinutes(minutes);
console.log(test + ' => ' + date);
}
I'm late to the party, but I thought I'd share a funtion that doesn't use regex:
function setDateTime(date, time) {
var index = time.indexOf("."); // replace with ":" for differently displayed time.
var index2 = time.indexOf(" ");
var hours = time.substring(0, index);
var minutes = time.substring(index + 1, index2);
var mer = time.substring(index2 + 1, time.length);
if (mer == "PM"){
hours = hours + 12;
}
date.setHours(hours);
date.setMinutes(minutes);
date.setSeconds("00");
return date;
}
Using moment.js will be the easy solution.
const fullDate = new Date();
// fullDate = Tue Dec 12 2017 11:18:30 GMT+0530 (IST) {}
const time = '01.00 AM';
const d = moment(fullDate).format('L'); // d = "12/12/2017"
const date = moment(d +' '+ time).format();
// date = "2017-12-12T01:00:00+05:30"
If you want convert moment date to js date
const jsDate = moment(date).toDate();
function getCurrentDate() {
var lDate = new Date();
var lDay = lDate.getDate();
var lMonth = lDate.getMonth() + 1;
var lYear = lDate.getFullYear();
if (lDay < 10) {
lDay = '0' + lDay
}
if (lMonth < 10) {
lMonth = '0' + lMonth
}
mCurrentDate = lYear + "-" + lMonth + "-" + lDay + "T00:00:00+05:30";
}
I added a few things as an improvement to the accepted answer by #thebreiflabb to suit my use case and thought i'd share.
if the regex is changed to timeReg = /(\d+)[\.|:](\d+)\s?(\w+)/;,
it'll handle a few other common cases.
namely:
using a colon instead of decimal point between hours and minutes
allowing am/pm to immediately follow the time with no space
also, setting the seconds to 0 (since that was my main use case)
the resulting code would be:
var test, parts, hours, minutes, date,
d = (new Date()).getTime(),
tests = ['01.25 PM', '01:25pm', '1:25 PM', '11.35 PM', '12.45 PM', '01.25 AM', '11.35 AM', '12.45 AM'],
i = tests.length,
timeReg = /(\d+)[\.|:](\d+)\s?(\w+)/;
for(; i-- > 0;) {
test = tests[i];
parts = test.match(timeReg);
hours = /am/i.test(parts[3]) ?
function(am) {return am < 12 ? am : 0}(parseInt(parts[1], 10)) :
function(pm) {return pm < 12 ? pm + 12 : 12}(parseInt(parts[1], 10));
minutes = parseInt(parts[2], 10);
date = new Date(d);
date.setHours(hours);
date.setMinutes(minutes);
date.setSeconds(0);
console.log(test + ' => ' + date);
}

How do I get the current time only in JavaScript

How can I get the current time in JavaScript and use it in a timepicker?
I tried var x = Date() and got:
Tue May 15 2012 05:45:40 GMT-0500
But I need only current time, for example, 05:45
How can I assign this to a variable?
var d = new Date("2011-04-20T09:30:51.01");
d.getHours(); // => 9
d.getMinutes(); // => 30
d.getSeconds(); // => 51
or
var d = new Date(); // for now
d.getHours(); // => 9
d.getMinutes(); // => 30
d.getSeconds(); // => 51
Short and simple:
new Date().toLocaleTimeString(); // 11:18:48 AM
//---
new Date().toLocaleDateString(); // 11/16/2015
//---
new Date().toLocaleString(); // 11/16/2015, 11:18:48 PM
4 hours later (use milisec: sec==1000):
new Date(new Date().getTime() + 4*60*60*1000).toLocaleTimeString(); // 3:18:48 PM or 15:18:48
2 days before:
new Date(new Date().getTime() - 2*24*60*60*1000).toLocaleDateString() // 11/14/2015
Get and set the current time efficiently using javascript
I couldn't find a solution that did exactly what I needed. I wanted clean and tiny code so I came up with this:
PURE JAVASCRIPT
function timeNow(i) {
var d = new Date(),
h = (d.getHours()<10?'0':'') + d.getHours(),
m = (d.getMinutes()<10?'0':'') + d.getMinutes();
i.value = h + ':' + m;
}
<a onclick="timeNow(test1)" href="#">SET TIME</a>
<input id="test1" type="time" value="10:40" />
UPDATE
There is now sufficient browser support to simply use: toLocaleTimeString
For html5 type time the format must be hh:mm.
function timeNow(i) {
i.value = new Date().toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
}
<a onclick="timeNow(test1)" href="#">SET TIME</a>
<input id="test1" type="time" value="10:40" />
Try it on jsfiddle
You can simply use this methods.
console.log(new Date().toLocaleTimeString([], { hour: '2-digit', minute: "2-digit", hour12: false }));
console.log(new Date().toLocaleTimeString([], { hour: '2-digit', minute: "2-digit" }));
Try
new Date().toLocaleTimeString().replace("/.*(\d{2}:\d{2}:\d{2}).*/", "$1");
Or
new Date().toTimeString().split(" ")[0];
const date = Date().slice(16,21);
console.log(date);
Do you mean:
var d = new Date();
var curr_hour = d.getHours();
var curr_min = d.getMinutes();
Try this:
var date = new Date();
var hour = date.getHours();
var min = date.getMinutes();
function getCurrentTime(){
var date = new Date();
var hh = date.getHours();
var mm = date.getMinutes();
hh = hh < 10 ? '0'+hh : hh;
mm = mm < 10 ? '0'+mm : mm;
curr_time = hh+':'+mm;
return curr_time;
}
This how you can do it.
const date = new Date();
const time = date.toTimeString().split(' ')[0].split(':');
console.log(time[0] + ':' + time[1])
See these Date methods ...
toLocaleTimeString - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString
toTimeString - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString
Try this
new Date().toTimeString().slice(0, 8);
or
new Date().toTimeString().split(" ")[0];
It should work.
this -
var x = new Date();
var h = x.getHours();
var m = x.getMinutes();
var s = x.getSeconds();
so-
x = date
h = hours
m = mins
s = seconds
A simple way to do this in ES6, in the format you requested (hh:mm), would be this way:
const goodTime = `${new Date().getHours()}:${new Date().getMinutes()}`;
console.log(goodTime);
(Obviously, the console logging is not part of the solution)
This is the shortest way.
var now = new Date().toLocaleTimeString();
console.log(now)
Here is also a way through string manipulation that was not mentioned.
var now = new Date()
console.log(now.toString().substr(16,8))
var today = new Date(); //gets current date and time
var hour = today.getHours();
var minute = today.getMinutes();
var second = today.getSeconds();
Simple functions to get Date and Time separated and with compatible format with Time and Date HTML input
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [year, month, day].join('-');
}
function formatTime(date) {
var hours = new Date().getHours() > 9 ? new Date().getHours() : '0' + new Date().getHours()
var minutes = new Date().getMinutes() > 9 ? new Date().getMinutes() : '0' + new Date().getMinutes()
return hours + ':' + minutes
}
getTime() {
let today = new Date();
let h = today.getHours();
let m = today.getMinutes();
let s = today.getSeconds();
h = h < 10 ? "0" + h : h;
m = m < 10 ? "0" + m : m;
s = s < 10 ? "0" + s : s;
let time = h + ":" + m + ":" + s;
return time;
},
Assign to variables and display it.
time = new Date();
var hh = time.getHours();
var mm = time.getMinutes();
var ss = time.getSeconds()
document.getElementById("time").value = hh + ":" + mm + ":" + ss;
This worked for me but this depends on what you get when you hit Date():
Date().slice(16,-12)
Here is how I'm doing this: (Hope it helps someone)
What I'm doing is validating the time that the user enters in the HTML time input is not in the past:
let inputTime = value; // from time input in html (06:29)
const splittedInputTime = inputTime.split(':');
let currentDate = new Date();
currentDate.setHours(splittedInputTime[0]);
currentDate.setMinutes(splittedInputTime[1]);
const finalInputTime = currentDate.toTimeString().split(" ")[0];
const currentTime = new Date().toTimeString().split(" ")[0];
// Returns a boolean (true/ false)
let validTime = finalInputTime >= currentTime;
Date.toLocaleTimeString() options
The Date.toLocaleTimeString() function can receive an options parameter to format the output
Some of the available options are these
new Date().toLocaleTimeString([], { timeStyle: "full" }) // 4:43:58 AM Pacific Standard Time
new Date().toLocaleTimeString([], { timeStyle: "long" }) // 4:43:58 AM PST
new Date().toLocaleTimeString([], { timeStyle: "medium" }) // 4:43:58 AM
new Date().toLocaleTimeString([], { timeStyle: "short" }) // 4:43 AM
Or you can specify the representation of the hour, minute, and second with these values:
"numeric" (e.g., 1)
"2-digit" (e.g., 01)
new Date().toLocaleTimeString([], { hour: '2-digit', minute: "2-digit" })
// 04:43 AM
Or set the 12-hour time using hour12: true or false
For more details take a look at
Date.toLocaleTimeString() parameters and
Intl.DateTimeFormat() options
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
console.log(strTime);
$scope.time = strTime;
date.setDate(date.getDate()+1);
month = '' + (date.getMonth() + 1),
day = '' + date.getDate(1),
year = date.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
var tomorrow = [year, month, day].join('-');
$scope.tomorrow = tomorrow;

Categories

Resources