JavaScript, wrong yyyy-mm-dd of today - javascript

I need to get the yyyy-mm-dd of today on const today2. I'm trying this:
const today = new Date();
console.log('today', today)
// today Wed Mar 11 2020 23:13:35 GMT-0300 (hora de verano de Chile)
const today2 = new Date().toISOString().slice(0,10);
console.log('today2', today2)
// today2 2020-03-12
I need to get 2020-03-11 but I'm getting 2020-03-12
why? I don't want to use moment

Try this:
const today = new Date();
const today2 = new Date(today.getTime() - (today.getTimezoneOffset() * 60000)).toISOString().slice(0,10);
Using toISOString() converts the timezone to UTC(standard time)

Try this function..
export const getTodayDate = () => {
var today = new Date();
var dd = (today.getDate()).toString();
var mm = (today.getMonth() + 1).toString();
var yyyy = (today.getFullYear()).toString();
if (parseInt(dd) < 10) {
dd = '0' + dd;
}
if (parseInt(mm) < 10) {
mm = '0' + mm;
}
return yyyy + '-' + mm + '-' + dd;
}
const today2 = getTodayDate();
console.log(today2);

I got it from: https://stackoverflow.com/a/50130338/3541320
const today = new Date();
const todayYYYMMDD = new Date(today.getTime() - (today.getTimezoneOffset() * 60000 ))
.toISOString()
.split("T")[0];

Related

Current Date converted to 10 days before and 10 days after

I have this code where I convert the current date to this format 2020-08-20 . But how do I alter it to give me the date 10 days from today and 10 days before today.
eg today is 2020-08-20 I am trying to get 10 days from today 2020-08-30
This is my code
const dateConverter = (dateIn) => {
var year = dateIn.getFullYear();
var month = dateIn.getMonth() + 1; // getMonth() is zero-based
var day = dateIn.getDate();
return year + "-" + month.toString().padStart(2, "0") + "-" + day.toString().padStart(2, "0");
}
var today = new Date();
console.log(dateConverter(today));
It's a little bit tricky. First set the hours from the date to 12 for avoiding problems with summer/wintertime-changing. Then use getDate add 10 for the extra days and setDate with the new value. Now you have a value in milliseconds, generate out of this a new date to get an dateobject. For the second date subtract 20 days because the original date was changed by the action before and do all other the same.
Format the output for the dates with getFullYear, getMonth and getDate
. Because month is handled in JS from 0 to 11 add 1 month. Months and days could be 1-digit but you want it 2 digits, so add before the string "0" and get the last 2 chars of it with slice.
Do the format for both dates and return them as array.
const dateConverter = (dateIn) => {
dateIn.setHours(12);
let dateIn10days = new Date(dateIn.setDate(dateIn.getDate() + 10));
let dateFor10days = new Date(dateIn.setDate(dateIn.getDate() - 20));
let strIn10Days = dateIn10days.getFullYear() + '-' + ('0' +(dateIn10days.getMonth()+1)).slice(-2) + '-' + ('0' + dateIn10days.getDate()).slice(-2);
let strFor10Days = dateFor10days.getFullYear() + '-' + ('0' +(dateFor10days.getMonth()+1)).slice(-2) + '-' + ('0' + dateFor10days.getDate()).slice(-2);
return [strFor10Days, strIn10Days];
}
let today = new Date();
console.log(dateConverter(today));
Try this
const dateConverter = (dateIn) => {
var year = dateIn.getFullYear();
var month = dateIn.getMonth() + 1; // getMonth() is zero-based
var day = dateIn.getDate();
return year + "-" + month.toString().padStart(2, "0") + "-" + day.toString().padStart(2, "0");
}
var today = new Date();
var numberOfDaysToAdd = 10;
var tenDaysPlus = today.setDate(today.getDate() + numberOfDaysToAdd);
console.log(dateConverter(today));
var today = new Date();
var numberOfDaysToSubtract = 10;
var tenDaysMinus = today.setDate(today.getDate() - numberOfDaysToSubtract);
console.log(dateConverter(today));
I would suggest you to use the moment library but you still want plain javascript
const convert = (date) => {
const pastDate = new Date(date)
pastDate.setDate(pastDate.getDate() - 10);
const futureDate = new Date(date)
futureDate.setDate(futureDate.getDate() + 10);
return { pastDate, futureDate }
}
call convert function with any date.
This code will help you
Reference JavaScript calculating date from today date to 7 days before
for after 10 days just just convert the - to +
const dateConverter = (dateIn) => {
var dates ={};
var days = 10; // Days you want to subtract
for(let i=0;i<days;i++){
var date = dateIn;
var last = new Date(date.getTime() - (i * 24 * 60 * 60 * 1000));
var day = last.getDate();
var month= last.getMonth()+1;
var year= last.getFullYear();
dates[i] = year + "-" + month.toString().padStart(2, "0") + "-" + day.toString().padStart(2, "0");
}
return dates
}
var today = new Date();
console.log(dateConverter(today));
I've been messing around that before as well.
But on this Stack Overflow you can find a really good answer:
Add days to JavaScript Date
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
var date = new Date();
alert(date.addDays(5));
This is the code taken from that post.
For subtracting days, just replace the "+ days" with "- days"
Hope this solved your problem!
You can convert all the dates to timestamp and then simply calculate with them:
const dateTimestamp = new Date("2020-10-10").getTime()
const milisecondsInADay = 60*60*24*1000
const milisecondsInTenDays = milisecondsInADay * 10
const beforeDate = new Date(dateTimestamp - milisecondsInTenDays)
const afterDate = new Date(dateTimestamp + milisecondsInTenDays)
console.log("before", beforeDate)
console.log("after", afterDate)
console.log("initially", new Date(dateTimestamp))

Trying to get rid of some letters in string

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>

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)

Convert UTC Date to dd/mm/yyyy Format

I am having some difficulties when trying to convert UTC Date format to dd/mm/yyyy in JavaScript:
var launchDate = attributes["launch_date"];
if (isBuffering) {
var date = new Date(launchDate);
var d = new Date(date.toLocaleDateString());
launchDate = ((d.getUTCMonth() + 1) + "/" + (d.getUTCDate() + 1) + "/" + (d.getUTCFullYear()));
}
I tried with this, but it returns me an invalid date. So I changed to this:
var launchDate = attributes["launch_date"];
if (isBuffering) {
var date = new Date(launchDate);
var d = formatDate(new Date(date.toLocaleDateString()));
launchDate = ((d.getUTCMonth() + 1) + "/" + (d.getUTCDate() + 1) + "/" + (d.getUTCFullYear()));
}
However, it still returning me invalid Date. I wonder is there any possible way to change the date format of Fri May 31 2013 17:41:01 GMT+0200 (CEST) to dd/mm/yyyy?
Thanks in advance.
var d = new Date();
var n = d.toLocaleDateString();
This will be more superior in build JS method!
function formatDate(d)
{
date = new Date(d)
var dd = date.getDate();
var mm = date.getMonth()+1;
var yyyy = date.getFullYear();
if(dd<10){dd='0'+dd}
if(mm<10){mm='0'+mm};
return d = dd+'/'+mm+'/'+yyyy
}
Try it:
Date.parseExact(Your_Date, 'dd/MM/yyyy').toString('MM/dd/yyyy');
or
Date.parseExact(Your_Date, 'MM/dd/yyyy').toString('dd/MM/yyyy');
Month is 0 indexed, but day is not. You don't need to add 1 to your day.
Also, you're formatting it for MM/dd/yyyy, not dd/MM/yyyy.
solution:
var launchDate = attributes["launch_date"];
if (isBuffering) {
var date = new Date(launchDate);
var d = formatDate(new Date(date.toLocaleDateString()));
launchDate = ((d.getUTCDate())+ "/" + (d.getUTCMonth() + 1) + "/" + (d.getUTCFullYear()));
}

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