JavaScript setHours() and getHours() [duplicate] - javascript

I am trying to subtract hours from a given date time string using javascript.
My code is like:
var cbTime = new Date();
cbTime = selectedTime.setHours(-5.5);
Where selectedTime is the given time (time that i pass as parameter).
So suppose selectedTime is Tue Sep 16 19:15:16 UTC+0530 2014
Ans I get is : 1410875116995
I want answer in datetime format.
Am I doing something wrong here? Or there is some other solution?

The reason is that setHours(), setMinutes(), etc, take an Integer as a parameter. From the docs:
...
The setMinutes() method sets the minutes for a specified date
according to local time.
...
Parameters:
An integer between 0 and 59, representing the minutes.
So, you could do this:
var selectedTime = new Date(),
cbTime = new Date();
cbTime.setHours(selectedTime.getHours() - 5);
cbTime.setMinutes(selectedTime.getMinutes() - 30);
document.write('cbTime: ' + cbTime);
document.write('<br>');
document.write('selectedTime: ' + selectedTime);

Well first off setting the hours to -5.5 is nonsensical, the code will truncate to an integer (-5) and then take that as "five hours before midnight", which is 7PM yesterday.
Second, setHours (and other functions like it) modify the Date object (try console.log(cbTime)) and return the timestamp (number of milliseconds since the epoch).
You should not rely on the output format of the browser converting the Date object to a string for you, and should instead use get*() functions to format it yourself.

According to this:
http://www.w3schools.com/jsref/jsref_sethours.asp
You'll get "Milliseconds between the date object and midnight January 1 1970" as a return value of setHours.
Perhaps you're looking for this:
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_sethours3
Edit:
If you want to subtract 5.5 hours, first you have to subtract 5 hours, then 30 minutes. Optionally you can convert 5.5 hours to 330 minutes and subtract them like this:
var d = new Date();
d.setMinutes(d.getMinutes() - 330);
document.getElementById("demo").innerHTML = d;

Use:
var cbTime = new Date();
cbTime.setHours(cbTime.getHours() - 5.5)
cbTime.toLocaleString();

try this:
var cbTime = new Date();
cbTime.setHours(cbTime.getHours() - 5.5)
cbTime.toLocaleString();

Related

How to add today's time to any date object and getISOString?

I have a ngbDatePicker which helps me to pick a date. Then it returns an object like this:
{year:2020,month:12,day:03}
I'd like to get an ISOString of this date with today's time(current). So if time is 18:42 I should be able to get something like this:
2020-12-03T18:42:00.000Z
To do that I parsed object and made date firstly
(model is the object holds date like above)
var date = new Date(this.model.year + "-" + this.model.month + "-" + this.model.day);
//then to add today's time I found solution below on the internet whcih didn't work for me
var date2 = new Date(date);
var isoDateTime = new Date(date2 .getTime() - (date2 .getTimezoneOffset() * 60000)).toISOString();
Here isoDateTime returns 2020-12-10T03:00:00.000Z which is not I want.
How to solve this?
Working stackblitz
Just take the time part of a Date object and combine it with this.model:
var date2 = new Date();
var date = new Date(this.model.year, this.model.month-1, this.model.day,
date2.getHours(), date2.getMinutes(), date2.getSeconds());
var isoDateTime = date.toISOString();
console.log(isoDateTime);
The month parameter is 0 based, so we have to substract 1 from the month.
Result (I chose Dec.1st 2020 in the Datepicker):
2020-12-01T19:22:42.000Z
Try on Stackblitz
You can create a single Date for the time and append it to values from the object:
function myISOString(obj) {
let z = n=>('0'+n).slice(-2);
return `${obj.year}-${z(obj.month)}-${z(obj.day)}T${new Date().toTimeString().substring(0,8)}`;
}
let obj = {year:2020, month:12, day: 3};
console.log(myISOString(obj));
PS the use of leading zeros like 03 for numbers should be avoided as once upon a time that notation indicated octal values (but not any more), so 09 might be confusing.

JavaScript Date Validation when using firefox [duplicate]

I am creating a datetime string that looks like this: 2010-07-15 11:54:21
And with the following code I get invalid date in Firefox but works just fine in Chrome
var todayDateTime = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + seconds;
var date1 = new Date(todayDateTime);
In firefox date1 is giving me an invalid date, but in chrome its working just fine what would the main cause be?
You can't instantiate a date object any way you want. It has to be in a specific way. Here are some valid examples:
new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
or
d1 = new Date("October 13, 1975 11:13:00")
d2 = new Date(79,5,24)
d3 = new Date(79,5,24,11,33,0)
Chrome must just be more flexible.
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
From apsillers comment:
the EMCAScript specification requires exactly one date format (i.e., YYYY-MM-DDTHH:mm:ss.sssZ) but custom date formats may be freely supported by an implementation: "If the String does not conform to that [ECMAScript-defined] format the function may fall back to any implementation-specific heuristics or implementation-specific date formats." Chrome and FF simply have different "implementation-specific date formats."
This works in all browsers -
new Date('2001/01/31 12:00:00 AM')
new Date('2001-01-31 12:00:00')
Format: YYYY-MM-DDTHH:mm:ss.sss
Details: http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15
Option 1 :
Suppose your timestring has a format that looks like this :
'2016-03-10 16:00:00.0'
In that case, you could do a simple regex to convert it to ISO 8601 :
'2016-03-10 16:00:00.0'.replace(/ /g,'T')
This would procude the following output :
'2016-03-10T16:00:00.0'
This is the standard datetime format, and thus supported by all browsers :
document.body.innerHTML = new Date('2016-03-10T16:00:00.0') // THIS IS SAFE TO USE
Option 2 :
Suppose your timestring has a format that looks like this :
'02-24-2015 09:22:21 PM'
Here, you can do the following regex :
'02-24-2015 09:22:21 PM'.replace(/-/g,'/');
This, too, produces a format supported by all browsers :
document.body.innerHTML = new Date('02/24/2015 09:22:21 PM') // THIS IS SAFE TO USE
Option 3 :
Suppose you have a time string that isn't easy to adjust to one of the well-supported standards.
In that case, it's best to just split your time string into different pieces and use them as individual parameters for Date :
document.body.innerHTML = new Date(2016, 2, 26, 3, 24, 0); // THIS IS SAFE TO USE
This works in most browsers as well
new Date('2001/01/31 12:00:00')
That is the format of
"yyyy/MM/dd HH:mm:ss"
If you still want to create date using dashes, you can use this format:
var date = new Date('2013-08-31T17:00:00Z')
But bear in mind, that it creates time according to UTC. Meaning, if you live in GMT+3 (3 hours ahead of GMT) timezone, it will add this timezone offset to the time. So the above example will have this value, if GMT+3 (note that it is hour 20:00 and not 17:00):
Sat Aug 31 2013 20:00:00 GMT+0300 (FLE Standard Time)
Be sure to add 'Z' letter at the end, because otherwise Chrome and Firefox will parse the string differently (one will add time offset and the other won't).
I was having a similar issue in both Firefox and Safari when working with AngularJS. For example, if a date returned from Angular looked like this:
2014-06-02 10:28:00
using this code:
new Date('2014-06-02 10:28:00').toISOString();
returns an invalid date error in Firefox and Safari. However in Chrome it works fine. As another answer stated, Chrome is most likely just more flexible with parsing date strings.
My eventual goal was to format the date a certain way. I found an excellent library that handled both the cross browser compatibility issue and the date formatting issue. The library is called moment.js.
Using this library the following code works correctly across all browsers I tested:
moment('2014-06-02 10:28:00').format('MMM d YY')
If you are willing to include this extra library into your app you can more easily build your date string while avoiding possible browser compatibility issues. As a bonus you will have a good way to easily format, add, subtract, etc dates if needed.
This should work for you:
var date1 = new Date(year, month, day, hour, minute, seconds);
I had to create date form a string so I have done it like this:
var d = '2013-07-20 16:57:27';
var date1 = new Date(d.substr(0, 4), d.substr(5, 2), d.substr(8, 2), d.substr(11, 2), d.substr(14, 2), d.substr(17, 2));
Remember that the months in javascript are from 0 to 11, so you should reduce the month value by 1, like this:
var d = '2013-07-20 16:57:27';
var date1 = new Date(d.substr(0, 4), d.substr(5, 2) - 1, d.substr(8, 2), d.substr(11, 2), d.substr(14, 2), d.substr(17, 2));
Simple Solution, This works with All Browsers,
var StringDate = "24-11-2017"
var DateVar = StringDate.split("-");
var DateVal = new Date(DateVar[1] + "/" + DateVar[0] + "/" + DateVar[2]);
alert(DateVal);
One situation I've run into was when dealing with milliseconds. FF and IE will not parse this date string correctly when trying to create a new date.
"2014/11/24 17:38:20.177Z"
They do not know how to handle .177Z. Chrome will work though.
This is what worked for me on Firefox and Chrome:
// The format is 'year-month-date hr:mins:seconds.milliseconds'
const d = new Date('2020-1-4 12:00:00.999')
// we use the `.` separator between seconds and milliseconds.
Good Luck...
There is a W3C specification defining possible date strings that should be parseable by any browser (including Firefox and Safari):
Year:
YYYY (e.g., 1997)
Year and month:
YYYY-MM (e.g., 1997-07)
Complete date:
YYYY-MM-DD (e.g., 1997-07-16)
Complete date plus hours and minutes:
YYYY-MM-DDThh:mmTZD (e.g., 1997-07-16T19:20+01:00)
Complete date plus hours, minutes and seconds:
YYYY-MM-DDThh:mm:ssTZD (e.g., 1997-07-16T19:20:30+01:00)
Complete date plus hours, minutes, seconds and a decimal fraction of a
second
YYYY-MM-DDThh:mm:ss.sTZD (e.g., 1997-07-16T19:20:30.45+01:00)
where
YYYY = four-digit year
MM = two-digit month (01=January, etc.)
DD = two-digit day of month (01 through 31)
hh = two digits of hour (00 through 23) (am/pm NOT allowed)
mm = two digits of minute (00 through 59)
ss = two digits of second (00 through 59)
s = one or more digits representing a decimal fraction of a second
TZD = time zone designator (Z or +hh:mm or -hh:mm)
According to YYYY-MM-DDThh:mmTZD, the example 2010-07-15 11:54:21 has to be converted to either 2010-07-15T11:54:21Z or 2010-07-15T11:54:21+02:00 (or with any other timezone).
Here is a short example showing the results of each variant:
const oldDateString = '2010-07-15 11:54:21'
const newDateStringWithoutTZD = '2010-07-15T11:54:21Z'
const newDateStringWithTZD = '2010-07-15T11:54:21+02:00'
document.getElementById('oldDateString').innerHTML = (new Date(oldDateString)).toString()
document.getElementById('newDateStringWithoutTZD').innerHTML = (new Date(newDateStringWithoutTZD)).toString()
document.getElementById('newDateStringWithTZD').innerHTML = (new Date(newDateStringWithTZD)).toString()
div {
padding: 10px;
}
<div>
<strong>Old Date String</strong>
<br>
<span id="oldDateString"></span>
</div>
<div>
<strong>New Date String (without Timezone)</strong>
<br>
<span id="newDateStringWithoutTZD"></span>
</div>
<div>
<strong>New Date String (with Timezone)</strong>
<br>
<span id="newDateStringWithTZD"></span>
</div>
In fact, Chrome is more flexible to deal with different string format. Even if you don't figure out its String format, Chrome still can successfully convert String to Date without error. Like this:
var outputDate = new Date(Date.parse(inputString));
But for Firefox and Safari, things become more complex. In fact, in Firefox's document, it already says: (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse)
A string representing an RFC2822 or ISO 8601 date (other formats may be used, but results may be unexpected).
So, when you want to use Date.parse in Firefox and Safari, you should be careful. For me, I use a trick method to deal with it. (Note: it might be not always correct for all cases)
if (input.indexOf("UTC") != -1) {
var tempInput = inputString.substr(0, 10) + "T" + inputString.substr(11, 8) + "Z";
date = new Date(Date.parse(tempInput));
}
Here it converts 2013-08-08 11:52:18 UTC to 2013-08-08T11:52:18Z first, and then its format is fit words in Firefox's document. At this time, Date.parse will be always right in any browser.
In Firefox, any invalid Date is returned as a Date object as Date 1899-11-29T19:00:00.000Z, therefore check if browser is Firefox then get Date object of string "1899-11-29T19:00:00.000Z".getDate(). Finally compare it with the date.
I have used following date format and it's working in all browser.
var target_date = new Date("Jul 17, 2015 16:55:22").getTime();
var days, hours, minutes, seconds;
var countdown = document.getElementById("countdown");
remaining = setInterval(function () {
var current_date = new Date().getTime();
var seconds_left = (target_date - current_date) / 1000;
days = parseInt(seconds_left / 86400);
seconds_left = seconds_left % 86400;
hours = parseInt(seconds_left / 3600);
seconds_left = seconds_left % 3600;
minutes = parseInt(seconds_left / 60);
seconds = parseInt(seconds_left % 60);
countdown.innerHTML = "<b>"+days + " day, " + hours + " hour, "
+ minutes + " minute, " + seconds + " second.</b>";
}, 1000);

setHours is not a function when converting time from string

I am trying to compare a time in string format to the current time. I've tried setting up two Date objects and calling .Now() on both of them, then on one of them adjusting the time to the time that is in string format by splitting it and parsing both the hours and minutes to integers, but I get the following error:
setHours is not a function
The 'cutoff' value I'm using is '15:00' and when following in the debugger I can see this splits in to split[0] = 15 and split[1] = 00 (this is before they are parsed into integers.
var cutoff = data.CutOff;
var split = cutoff.split(":");
var today = Date.now();
var hours = parseInt(split[0]);
var min = parseInt(split[1]);
today.setHours(hours, min);
if (Date.now() < today) {
// Do Something
}
You want to do new Date() as opposed to Date.now()
new Date creates a Date instance which allows you to access the Date methods.
Date.now() method returns the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC.

How can I get todays timestamp at 4pm?

I am looking for a way to receive the timestamp of today's 4pm in JavaScript.
When I use this code
Math.floor(Date.now() / 1000);
it give me the current timestamp. How can I specify just the hour to be static, the rest to rely on the current day?
You can do this by getting the current DateTime and change the hour, code:
var d = new Date();
d.setHours(16,0,0,0);//The setHours method can take optional minutes, seconds and ms arguments, but you can also do setHours(16)
Math.floor(d / 1000);
Here is the code to do that:
var d = new Date();//stores current date time
d.setHours(16);//4pm = 16 in 24 hour time
Now when you'll type console.log(d), you'll get the following required result.
Tue May 12 2015 20:58:24 GMT+0500 (PKT)
Try:
var date = new Date();
date.setHours(16);
date.setMinutes(0);
date.setSeconds(0);
Math.floor(date.getTime() / 1000);
Instantiate a Date object and set the hours like so:
var d = new Date;
d.setHours(16);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours

Convert dd-mm-yy to javascript date object

I get a date which comes in this format: ddmmyy, and I need to do some validation with it.
How can I parse it to a javascript date object?
I've tried to search, and there are a lot on the ddmmyyyy format, but not the format I get.
EDIT: Example date: 031290 = 3.12.1990.
You could parse ddmmyyyy into a yyyy-mm-dd form and pass that to Date.parse.
Date.parse( "02032002".replace(/^(\d\d)(\d\d)(\d{4})$/, "$3-$2-$1") );
Or otherwise split it up and use the Date's setters / constructor:
// month - 1 : in this form January is 0, December is 11
var date = new Date( year, month - 1, date );
Just noticed the YY vs YYYY part of the question:
var parts = /^(\d\d)(\d\d)(\d{2})$/.exec( "190304" );
var date = new Date( parts[3], parts[2]-1, parts[1] );
You could augment that with some code which adds a 20 or 19 depending if the year is over or below a certain threshold (like 70 : < 70 indicates 20xx and >= 70 indictaes 19xx years).
Try this:
var a="221178".split(/(?=(?:..)*$)/);
var result=new Date ( parseInt(a[2],10) + 1900 , a[1]-1 , a[0] )
result:
Tue Nov 22 1978 00:00:00 GMT+0200
JSBIN
If you want a non-regex solution, you can use new Date(year, month, date) constructor, and simple cut strings into those parts. It's not fancy, but it clear in what it does:
function parse2date(str){
var year = parseInt(str.substr(4, 2));
var month = parseInt(str.substr(2, 2));
var day = parseInt(str.substr(0, 2))
return new Date(year < 20 ? 2000 + year : year, month - 1, day)
}
this function assumes if 2-disgit years is below 20 - then it is meant to be in 2000s, otherwise it's in 1900s. But you can adjust the limit. Try calling it:
alert(parse2date('031290'));
Ok, so here is how I solved it.
The answers here is right, except I wasn't happy with the way the detection of the current century worked; so I basically did this:
var date = new Date(year + 2000, month - 1, day);
if (date > new Date())
date.setYear(year + 1900);
With this code, I can maximum validate an age of 100, but that shouldn't be a problem.
Mukul Goel in the comment below points out it can only validate dates in the future. Probably right, I haven't checked it myself.

Categories