I am trying to make a filter based on hours for timestamps (in this example filter for all times after 8 am):
var beginningTimeValue = new Date('2020-01-01 08:00:00');
var unique = [["value","value","value","value","12/01/2021 00:03:35","value"],["value","value","value","value","01/01/2020 00:03:35","value"], ["value","value","value","value","01/01/2020 08:03:35","value"], ["value","value","value","value","01/01/2020 13:03:35","value"]]
if(!beginningTimeValue == ""){
unique = unique.filter(function(row)
{
var rYear = row[4].substring(6, 10);
var rMonth = row[4].substring(3, 5);
var rDay = row[4].substring(0, 2);
var rHour = row[4].substring(11, 13);
var rMinute = row[4].substring(14, 16);
var rSecond = row[4].substring(17, 19);
var bTime = new Date(parseInt(rYear, 10), parseInt(rMonth, 10), parseInt(rDay, 10), parseInt(rHour, 10), parseInt(rMinute, 10), parseInt(rSecond, 10));
console.log("ODATE = " + rYear + "/" + rMonth + "/" + rDay + "_" + rHour + ":" + rMinute + ":" + rSecond);
console.log("BDATE = " + bTime.getFullYear() + "/" + bTime.getMonth() + "/" + bTime.getDate() + "_" + bTime.getHours() + ":" + bTime.getMinutes() + ":" + bTime.getSeconds());
beginningTimeValue.setYear(bTime.getYear());
beginningTimeValue.setMonth(bTime.getMonth());
beginningTimeValue.setDate(bTime.getDate());
if(bTime.getTime() >= beginningTimeValue.getTime()){
console.log(bTime.getTime()*24*3600*1000 + " VS " + beginningTimeValue.getTime()*24*3600*1000);
}
else{
console.log("FALSE");
}
return bTime.getTime() >= beginningTimeValue.getTime();
}
);
}
console.log(unique);
I have debugged my way to finding out that I wouldn't get a FALSE value in the 2nd IF, however I am at a loss as to why the .getTime() function returns vastly different values for my console log:
"136556220816000000000 VS -5.0438323821312e+21"
"136560264336000000000 VS -5.0438323821312e+21"
The problem is in the following line:
beginningTimeValue.setYear(bTime.getYear());
The (deprecated) getYear() function returns
[a] number representing the year of the given date, according to local
time, minus 1900.
The (also deprecated) setYear() function
[...] interprets any two-digit number as an offset to 1900
In your case, getYear() returns a value like 121, which is not a two-digit number. When you subsequently invoke setYear() with that value, you get a date that is set to the year 121 instead of 2021.
Since getTime() returns the number of milliseconds since 1970, and 121 is before 1970, you get a negative number.
TL;DR: use getFullYear() and setFullYear() instead of getYear() and setYear().
Related
I'm trying to create a function that takes a number and returns a timestamp (HH:mm) using date-fns version 1.30.1 or plain JavaScript.
What I'm trying to achieve is to help a user when entering a time. I'm using Vue.js to update the field when a user moves away from the input field. So if a user types 21 then moves away, the field would ideally update to 21:00.
Some examples would be:
21 = 21:00
1 = 01:00
24 = 00:00
2115 = 21:15
Numbers like 815 does not have to return 08:15. Numbers like 7889 should return an error.
I have tried using regex:
time = time
.replace(/^([1-9])$/, '0$1')
.replace(/^([0-9]{2})([0-9]+)$/, '$1:$2')
.replace(/^24/, '00:00')
I have also tried using the parse method in date-fns but can't seem to wrap my head around how to solve this.
Version 1, converting anything less than 100 to hours
const num2time = num => {
if (num < 100) num *=100;
const [_,hh,mm] = num.toString().match(/(\d{1,2})(\d{2})$/)
return `${hh.padStart(2,"0")}:${mm}`
}
console.log(num2time(8));
console.log(num2time(2115));
console.log(num2time(15));
console.log(num2time("8"));
console.log(num2time("2115"));
version 2 can be used if the digits are always representing valid (h)hmm
const num2time = num => num.toString().replace(/(\d{1,2})(\d{2})$/,"$1:$2");
console.log(num2time(815));
console.log(num2time(2115));
console.log(num2time("2115"));
Conversion based on <100 (hours-only) and >=100 (100*hours+minutes), plus some fight with 24 and single-digit numbers (both hours and minutes):
function num2time(num){
var h,m="00";
if(num<100)
h=num;
else {
h=Math.floor(num/100);
m=("0"+(num%100)).slice(-2);
}
h=h%24;
return ("0"+h).slice(-2)+":"+m;
}
console.log(num2time(8));
console.log(num2time(801));
console.log(num2time(24));
console.log(num2time(2401));
console.log(num2time(2115));
console.log(num2time("8"));
console.log(num2time("2115"));
Original answer, kept for the comment only, but would not handle 24 or single-digit minutes correctly:
For example you can do a very mechanical conversion
function num2time(num){
if(num<10)
t="0"+num+":00";
else if(num<100)
t=num+":00";
else {
if(num<1000)
t="0"+Math.floor(num/100);
else if(num<2400)
t=Math.floor(num/100)
else
t="00";
t+=":"+(num%100);
}
return t;
}
console.log(num2time(8));
console.log(num2time(2115));
console.log(num2time("8"));
console.log(num2time("2115"));
Example verification:
function num2time(num){
var h,m="00";
if(num<100)
h=num;
else {
h=Math.floor(num/100);
m=("0"+(num%100)).slice(-2);
}
if(h<0 || h>24) throw "Hour must be between 0 and 24"
if(m<0 || m>59) throw "Minute must be between 0 and 59"
h=h%24;
return ("0"+h).slice(-2)+":"+m;
}
var numstr=prompt("Enter time code");
while(true) {
try {
console.log(num2time(numstr));
break;
} catch(ex) {
numstr=prompt("Enter time code, "+numstr+" is not valid\n"+ex);
}
}
You can use the first char as hour and last char as minute, you've to pad 0 on when there is less than 4 chars.
When there is 1 or 0 char you need to pad both left and right.
When there is 2 or 3 char you only pad right.
time_str = '230'
date = new Date('1970-01-01T' + time_str.slice(0,2).padStart(2,"0") + ':' + time_str.slice(2,4).padEnd(2,"0") + 'Z');
console.log(date)
console.log(("0" + date.getUTCHours()).slice(-2) + ":" + ("0" + date.getUTCMinutes()).slice(-2))
time_str = '24'
date = new Date('1970-01-01T' + time_str.slice(0,2).padStart(2,"0") + ':' + time_str.slice(2,4).padEnd(2,"0") + 'Z');
console.log(date)
console.log(("0" + date.getUTCHours()).slice(-2) + ":" + ("0" + date.getUTCMinutes()).slice(-2))
time_str = '3'
date = new Date('1970-01-01T' + time_str.slice(0,2).padStart(2,"0") + ':' + time_str.slice(2,4).padEnd(2,"0") + 'Z');
console.log(date)
console.log(("0" + date.getUTCHours()).slice(-2) + ":" + ("0" + date.getUTCMinutes()).slice(-2))
time_str = '78'
date = new Date('1970-01-01T' + time_str.slice(0,2).padStart(2,"0") + ':' + time_str.slice(2,4).padEnd(2,"0") + 'Z');
console.log(date)
console.log(("0" + date.getUTCHours()).slice(-2) + ":" + ("0" + date.getUTCMinutes()).slice(-2))
DateFns implementation
IMHO, working on adding and removing minutes and hours is a cleaner way to manage this transform:
function formattedTime(val) {
let helperDate;
if(val.length <= 2) {
if(val > 24)return 'error';
helperDate = dateFns.addHours(new Date(0), val-1);
return dateFns.format(helperDate, 'HH:mm');
}
if(val.length > 2) {
let hhmm = val.match(/.{1,2}/g);
if(hhmm[0] > 24 || hhmm[1] > 60) return 'error';
helperDate = dateFns.addHours(new Date(0), hhmm[0]-1);
helperDate = dateFns.addMinutes(helperDate, hhmm[1]);
return dateFns.format(helperDate, 'HH:mm');
}
}
const myArr = [21, 1, 24, 2115, 815];
myArr.forEach(
val => console.log(formattedTime(val.toString()))
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.min.js"></script>
I want to compare two times
So I tried these:
"01:03 AM" > "01:02 AM"
> true
"01:01 AM" > "01:02 AM"
> false
In these cases the results were correct, but not in this one:
"12:55 AM" > "03:55 AM"
> true
How can I compare two times in this format "hh:mm tt" with proper accuracy?
Is it necessary to include the dates with the times, and then compare the dates and times?
Update: Since space separated date is not supported by safari, using slash instead of space works across all browsers.
You'll need to convert the time into Date Object first and then into timestamp. Then you can compare the timestamp. You can follow this basic example:
var t = new Date();
d = t.getDate();
m = t.getMonth() + 1;
y = t.getFullYear();
//Convert time into date object
var d1 = new Date(m + "/" + d + "/" + y + " " + "12:55 AM");
var d2 = new Date(m + "/" + d + "/" + y + " " + "03:55 AM");
//Get timestamp
var t1 = d1.getTime();
var t2 = d2.getTime();
t1 > t2 ? alert("t1 greater than t2") : alert("t2 greater than t1");
But for the complicated time comparison, you should use a plugin.
Convert the time to minutes and compare
function toMin(str) {
var match = str.match(/(\d+):(\d+)\s(AM|PM)/)
var min = (+match[1] > 11 ? 0 : match[1] * 60) + +match[2];
if (match[3].toLowerCase() == 'pm') {
min += 720;
}
return min;
}
function gt(v1, v2) {
snippet.log(v1 + ' > ' + v2 + ': ' + (toMin(v1) > toMin(v2)))
}
function lt(v1, v2) {
snippet.log(v1 + ' < ' + v2 + ': ' + (toMin(v1) < toMin(v2)))
}
//then
gt('12:30 AM', '01:00 AM');
lt('12:30 AM', '01:00 AM');
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
I want to get the date and time in the following format:
yyyy.mm.dd.hh.mm.ss | 2014.11.6.20.31.24
However, my code (based on Get Current Time) is instead providing these values:
y??.m?.d?.hh.mm.ss | 114.10.4.20.31.24
Here is my code:
var dt = new Date();
var time = dt.getHours() + "." + dt.getMinutes() + "." + dt.getSeconds();
var date = dt.getYear() + "." + dt.getMonth() + "." + dt.getDay();
alert(date + "." + time);
Can someone please let me know why these odd values are in there 114.10.4 and how to change them to be what I want?
That is because you need to use
.getFullYear() for the full year
the .getMonth() is 0-based so you need to add 1
the function to get the day of month is .getDate(). The .getDay() is for the day of the week.
var dt = new Date();
var time = dt.getHours() + "." + dt.getMinutes() + "." + dt.getSeconds();
var date = dt.getFullYear() + "." + (dt.getMonth()+1) + "." + dt.getDate();
alert(date + "." + time);
If, for some weird reason, you are going only for firefox, you can use
var d = new Date(),
formatted = d.toLocaleFormat('%Y.%m.%d.%H.%M.%S');
alert(formatted);
Finally, you can use the great moment.js library and do
var formatted = moment().format('YYYY.MM.DD.HH.mm.ss');
You are using the wrong getters. Use getFullYear() instead of getYear(), and getDate() instead of getDay(). And add 1 to the month, because it starts at 0.
var dt = new Date();
var time = dt.getHours() + "." + dt.getMinutes() + "." + dt.getSeconds();
var date = dt.getFullYear() + "." + (dt.getMonth() + 1) + "." + dt.getDate();
alert(date + "." + time);
Just make sure that you are using methods what you want to use e.g:
dt.getYear() => dt.getFullYear()
For further reference see this.
should use getFullYear() instead of getYear() and getMonth() + 1 instead of getMonth() because it calculate form 0..11 and info about getDay()
var dt = new Date();
var time = dt.getHours() + "." + dt.getMinutes() + "." + dt.getSeconds();
var date = dt.getFullYear() + "." + dt.getMonth() + 1 + "." + dt.getDate();
alert(date + "." + time);
dt.getDay() this day of the week
The getDay() method returns the day of the week (from 0 to 6)
You need to use getDate() to know the number of the day (from 1 to 31)
Also, you need to add 1 to getMonth() because months in JavaScript starts on 0
I get the response for the Date in this format while showing in the text box, how do i covert it to MM/DD/YYYY and Again re covert it to back to this format while sending
/Date(1306348200000)/
function dateToString(date) {
return (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getYear();
}
function dateFromString(str) {
return new Date(str);
}
Note, that month begins from 0.
To convert the regExp-like string to a real Date Object you could use:
var dateNum = Number('/Date(1306348200000)/'.replace(/[^0-9]/g,''))
, dat = new Date(dateNum); //=>Date {Wed May 25 2011 20:30:00 GMT+0200}
To display formatted dates I use my own small library, which may be of use to you.
var s = '/Date(1306348200000)/';
// convert to javascript date
var date = new Date(parseInt(s.substr(6, 13))); // removes /Date( & )/
// format the date
function pad(n) { return n < 10 ? '0' + n : n; } // leading zeros
var ddmmyy = pad(date.getDate()) + '/' + pad(date.getMonth() + 1) + '/' + date.getFullYear().toString().substr(2);
// convert back
s = '/Date(' + date.getTime() + ')/';
here you can find everything regarding javascript dates http://www.w3schools.com/js/js_obj_date.asp
For using the Amazon mechanical turk API I want to get the current GMT time and show it in ISO format
2011-02-24T20:38:34Z
I am wondering if there is any way to correctly get the gmt time and also be able to reformat it with ISO format. I can use something like now.toGMTString(); but it makes a string out of the date and it is hard to reformat it with ISO.
var year = now.getUTCFullYear()
var month = now.getUTCMonth()
var day= now.getUTCDay()
var hour= now.getUTCHours()
var mins= now.getUTCMinutes()
var secs= now.getUTCSeconds()
var dateString = year + "-" + month + "-" + day + "T" + hour + ":" + mins + ":" + secs + "Z"
You should be using UTC now instead of GMT. (Amounts to almost the same thing now, and it is the new standard anyway)
I believe this will work for you:
Number.prototype.pad = function(width,chr){
chr = chr || '0';
var result = this;
for (var a = 0; a < width; a++)
result = chr + result;
return result.slice(-width);
}
Date.prototype.toISOString = function(){
return this.getUTCFullYear().pad(4) + '-'
+ this.getUTCMonth().pad(2) + '-'
+ this.getUTCDay().pad(2) + 'T'
+ this.getUTCHours().pad(2) + ':'
+ this.getUTCMinutes().pad(2) + ':'
+ this.getUTCSeconds().pad(2) + 'Z';
}
Usage:
var d = new Date;
alert('ISO Format: '+d.toISOString());
Not much more different than every else's answer, but make it built-in to the date object for convenience
function pad(num) {
return ("0" + num).slice(-2);
}
function formatDate(d) {
return [d.getUTCFullYear(),
pad(d.getUTCMonth() + 1),
pad(d.getUTCDate())].join("-") + "T" +
[pad(d.getUTCHours()),
pad(d.getUTCMinutes()),
pad(d.getUTCSeconds())].join(":") + "Z";
}
formatDate(new Date());
Output:
"2011-02-24T21:01:55Z"
This script can take care of it
/* use a function for the exact format desired... */
function ISODateString(d){
function pad(n){return n<10 ? '0'+n : n}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'}
var d = new Date();
document.write(ISODateString(d)); // prints something like 2009-09-28T19:03:12Z