Trying to get rid of some letters in string - javascript

let myDate = new Date();
myDate.toLocaleString;
So if I'll console log the value of myDate will be:
Wed Oct 16 2019 15:57:22 GMT+0300 (Israel Daylight Time)
What if I want the value to be only 57:22? (Minutes and seconds of the hour).
How do I do that?

Have a go with this
const getMMSS = (str) => str.match(/:\d{2}:\d{2}/)[0].slice(1);
// tests
const myDate = new Date(2019,09,16,23,59,59,999);
let dateStr = myDate.toLocaleString();
console.log(getMMSS(dateStr))
dateStr = "Wed Oct 16 2019 15:57:22 GMT+0300 (Israel Daylight Time)"
console.log(getMMSS(dateStr))
Or just
const pad = (num) => ("0"+num).slice(-2);
const myDate = new Date();
console.log(`${pad(myDate.getMinutes())}:${pad(myDate.getSeconds())}`)

You can use Date's own methods to do this:
let date = new Date();
let m = date.getMinutes();
let s = date.getSeconds();
console.log(m + ':' + s);
To make the final result more readable you can check if the minutes and seconds are smaller than 10 and, if so, append a 0 to the beginning:
let date = new Date();
let m = date.getMinutes();
let s = date.getSeconds();
m = m < 10 ? ('0' + m) : m;
s = s < 10 ? ('0' + s) : s;
console.log(m + ':' + s);

You may use basic javascript Date methods:
var myDate = new Date();
var formatted =`${myDate.getMinutes()}:${myDate.getSeconds()}`;
console.log(formatted);
OR using moment.js library
var myDate = new Date();
var formatted = moment(myDate).format("mm:ss");
console.log(formatted);
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>

Related

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)

substract 5 minute from current Date and time javascript

I have problem while substracting time from current date. My Code looks like:
var d = new Date(),
year = d.getUTCFullYear(),
month = ('0'+(d.getUTCMonth()+1)).slice(-2),
day = ('0'+d.getUTCDate()).slice(-2),
hour = ('0'+d.getUTCHours()).slice(-2),
minute = ('0'+d.getUTCMinutes()).slice(-2),
second = ('0'+d.getUTCSeconds()).slice(-2);
var startDate = year+'/'+month+'/'+day+'-'+hour+':'+minute+':'+second;
console.log(startDate);
You can simply use like below
var fiveMinuteAgo = new Date( Date.now() - 1000 * (60 * 5) )
Get the milliseconds of the date variable, substract 5 minutes and create a new date object from it:
var d = new Date()
// d = Mon Feb 29 2016 08:00:09 GMT+0100 (W. Europe Standard Time)
var milliseconds = Date.parse(d)
// 1456729209000
milliseconds = milliseconds - (5 * 60 * 1000)
// - 5 minutes
d = new Date(milliseconds)
// d = Mon Feb 29 2016 07:55:04 GMT+0100 (W. Europe Standard Time)
If you are ready to use new date manipulation js called as moment js.
You can simply do it in one function as below:
moment().subtract(5, 'minutes');
Moment JS Docs
You could use like this
var original = new Date();
var subtract5min = new Date();
alert("before : " + original);
subtract5min.setTime(original.getTime() - 5*60*1000);
alert("after : " + subtract5min);
You can simply substract by
minute = ('0'+d.getUTCMinutes()).slice(-2)-5
var d = new Date(),
year = d.getUTCFullYear(),
month = ('0'+(d.getUTCMonth()+1)).slice(-2),
day = ('0'+d.getUTCDate()).slice(-2),
hour = ('0'+d.getUTCHours()).slice(-2),
minute = ('0'+d.getUTCMinutes()).slice(-2),
second = ('0'+d.getUTCSeconds()).slice(-2);
if (minute>=5)
minute = minute-5;
else {
minute = (parseInt(minute) + 60) - 5;
hour = hour - 1;
}
var startDate = year+'/'+month+'/'+day+'-'+hour+':'+minute+':'+second;
alert(startDate);

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;

javascript: get month/year/day from unix timestamp

I have a unix timestamp, e.g., 1313564400000.00. How do I convert it into Date object and get month/year/day accordingly? The following won't work:
function getdhm(timestamp) {
var date = Date.parse(timestamp);
var month = date.getMonth();
var day = date.getDay();
var year = date.getYear();
var formattedTime = month + '/' + day + '/' + year;
return formattedTime;
}
var date = new Date(1313564400000);
var month = date.getMonth();
etc.
This will be in the user's browser's local time.
An old question, but none of the answers seemed complete, and an update for 2020:
For example: (you may have a decimal if using microsecond precision, e.g. performance.now())
let timestamp = 1586438912345.67;
And we have:
var date = new Date(timestamp); // Thu Apr 09 2020 14:28:32 GMT+0100 (British Summer Time)
let year = date.getFullYear(); // 2020
let month = date.getMonth() + 1; // 4 (note zero index: Jan = 0, Dec = 11)
let day = date.getDate(); // 9
And if you'd like the month and day to always be a two-digit string (e.g. "01"):
let month = (date.getMonth() + 1).toString().padStart(2, '0'); // "04"
let day = date.getDate().toString().padStart(2, '0'); // "09"
For extended completeness:
let hour = date.getHours(); // 14
let minute = date.getMinutes(); // 28
let second = date.getSeconds(); // 32
let millisecond = date.getMilliseconds(); // 345
let epoch = date.getTime(); // 1586438912345 (Milliseconds since Epoch time)
Further, if your timestamp is actually a string to start (maybe from a JSON object, for example):
var date = new Date(parseFloat(timestamp));
or for right now:
var date = new Date(Date.now());
More info if you want it here (2017).
Instead of using parse, which is used to convert a date string to a Date, just pass it into the Date constructor:
var date = new Date(timestamp);
Make sure your timestamp is a Number, of course.

Categories

Resources