I have an array of 2 strings, both of which are in Unix time.
[1484930449590,1548002449590]
Converting these back into human readable time gives me today's date and the date 2 years ago.
However, when I parse both of these timestamps with MomentJS:
const start = moment(timeRange[0])
const end = moment(timeRange[1])
I receive the following values:
moment("2001-01-01T00:00:00.000")
moment("2001-04-01T00:00:00.000")
For some reason, momentJS converts both of the timestamps to the year 2001, even though the years should be 2019 and 2017.
Parsing the strings first does not make things better:
const start = moment(parseInt(timeRange[0]))
const end = moment(parseInt(timeRange[1]))
Now start and end are:
moment("1969-12-31T19:00:00.001")
moment("1969-12-31T19:00:00.004")
Does anyone know what is going on?
I tried the following solution:
console.log(timeRange)
const start = moment(parseInt(timeRange[0]) / 1000)
console.log(start)
const end = moment(parseInt(timeRange[1]) / 1000)
console.log(end)
but nothing changed:
1484931697215,1548003697215
moment("1969-12-31T19:00:00.000")
moment("1969-12-31T19:00:00.000")
Update:
The issue is that I was wrong about timeRange being an array. Rather, it was actually a string. This happened because on the client-side timeRange was an array, but when it got sent as a GET request to the server and retrieved with const timeRange = req.query.timeRange, it got converted to a string.
Your timestamp is in milliseconds, not in seconds. Try dividing by 1000 first:
const start = moment(parseInt(timeRange[0]/1000))
const end = moment(parseInt(timeRange[1]/1000))
That should give you the correct date
The issue is that I was wrong about timeRange being an array. Rather, it was actually a string. This happened because on the client-side timeRange was an array, but when it got sent as part of a GET request to the server and retrieved with const timeRange = req.query.timeRange, it got converted to a string.
The solution was to reconvert the timeRange back into an array:
const times = req.query.timeRange.split(",")
const startDate = moment(parseInt(times[0]))
const endDate = moment(parseInt(times[1]))
Related
month ago I was working on weather website, and finished it,
I have 5 content card there and each card discribes each day of weather and on top of card I have included week day, when I make API request I get date format like that 6-21-2021, I try to align this date string, to make readable for new Date() in Javascript to pull correct number of week day from Javascript Method
this is what I do
const weekDays: string[] = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday",];
//this part is included in get request
const dateFormatAPI = (response.data.list[0].dt_txt).split("-") //6-21-2021 -> ["6", "21", "2021"]
const alignedDate: string = String([dateFormatAPI[1],dateFormatAPI[2],dateFormatAPI[0]]) //"21, 6, 2021"
.replace(",", "-")
.replace(",", "-") //Output: 21-6-2021
const date = new Date(alignedDate); //putting this format in Date Method
console.log(days[date.getDay()]) //and getting current number putting this as array index and get week day
it outputs week day, But it only outputs on Windows computer, and on Android
when I let to my friened check my website on IOS, she got error instead of showing week day she was getting undefined
and I have question why happens like that? how can I fix it?
if you use IOS right now, you can check on your own this website Weather Website
Parsing a string to create another string that is parsed by the built–in parser is not a good idea, see Why does Date.parse give incorrect results?
"21-6-2021" is not a format supported by ECMA-262 so parsing is implementation dependent and iOS treats it as an invalid date.
A library can help, but isn't necessary. To parse the string try:
let s = '6-21-2021';
// Split on non–digit character
let [m, d, y] = s.split(/\D/);
// Use the Date constructor
let date = new Date(y, m - 1, d);
console.log(date.toDateString());
console.log(date.getDay());
console.log(date.toLocaleString('default',{weekday:'long'}));
For example, I have this string "2020-09-09T21:00:14.114-04:00"
I grab this from my database and in its current form, it is a string. my goal is to have it display
4 PM instead of the long string of jibberish
is it possible to accomplish this?
I was thinking of possibly creating a new date object like
let test = new Date('2020-09-09T21:00:14.114-04:00').
but I'm stuck at the parsing and formatting part. it would be better to have this be done while the current state is a string but I don't think that this would be possible
edit: i would like the desired output to be the hour:minute and then am/pm
ex 10:15pm
You can do that by parsing the date from your database using Date.parse().
Then you can get the time or whatever you need using date.toLocalTimeString() in your case.
let dateUnix = Date.parse('2020-09-09T21:00:14.114-04:00');
const time = new Date(dateUnix).toLocaleTimeString();
console.log(time); // --> "4:00:14 AM"
The Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31).
Here's some useful resources MDN Date.parse()
MDN Date.toLocalTimeString()
You can do as following way.new Date() is used to get the current date and time.
var today = new Date();
var time = today.getHours();
if(time>12){
var new_time= time % 12;
}
else{
var new_time= time;
}
I have a epoch/unix timestamp which I have, which I get after running the journalctl -o json-pretty -f command. So I get my "__REALTIME_TIMESTAMP" : "1576681153604871" value from a given log. I want to convert this to an ISOString format, so I use the below code
var result;
time = parseInt(time);
var msec = time/1000; // convert __REALTIME_TIMESTAMP to milliseconds from microseconds
var myDate = new Date(msec);
var isoDate = myDate.toISOString();
I get the output as below
"2019-12-18T14:25:49.605Z"
I wish to even display the microsecond part in this something like
"2019-12-18T14:25:49.605762Z"
but myDate.toISOString() doesn't work properly if I don't convert the epoch to milliseconds.
I dont know if time % 1000 is the right way, to extract the microsecond part and then append it to get the desired output .
So is there a way to get the output in microsecond format ?
So is there a way to get the output in microsecond format ?
Not using built–in methods. You can add the microsecond part yourself though. It's best to use string methods to get the digits to preserve leading zeros:
// Time value in microseconds
let tv = 1576681153064071;
// Get millisecond part
let msec = tv/1000;
// Get microsecond part - keep leading zeros
let μsec = String(tv).slice(-3);
// Get ISO 8601 timestamp
let isoDate = new Date(msec).toISOString();
// Add in microseconds
let isoDatePlus = isoDate.replace('Z', μsec + 'Z');
console.log(isoDatePlus);
It might be better to replace the entire decimal part though, just in case some future implementation decides to add more digits after the decimal place.
let tv = 1576681153064071;
let isoDate = new Date(tv/1e3).toISOString().replace(/\d+Z$/, String(tv).slice(-6) + 'Z');
console.log(isoDate);
Modifying #RobG's example, the technically correct and faster code would be
let tv = 1576681153064071;
let isoDate = new Date(tv/1e3).toISOString().slice(0, -4) + String(tv).slice(-6).padStart(6, '0') + 'Z';
console.log(isoDate);
// Less than 6 digits microseconds example
let smallTs = 50
console.log(new Date(smallTs/1e3).toISOString().slice(0, -4) + String(smallTs).slice(-6).padStart(6, '0') + 'Z');
RobG example cannot convert smaller than 6 Digits microseconds like 500 or 50 to ISO String correctly. Thank you for your answer though.
In This Meteor server side code for the users collections, the property createdAt shows something like this ISODate("2017-02-09T01:22:30.894Z").
And in another collection myCol I have the createdAt property with the unix timestamp in milliseconds.
Moment.js is installed.
How can I check the following condition:
myCol.createdAt is after n months from the end of the month when the user was created. thx
Here is one approach that should work (there are of course a handful of other ways to do this...this was the first one that came to mind).
You can convert the Users createdAt property to a moment object like this (assuming your user doc is stored in a var called userOne).
var moment1 = moment(userOne.createdAt);
Then, you can convert the unix timestamp in the other collection like this (assuming the doc is stored in a var called doc).
var moment2 = moment(doc.createdAt);
Now find the end of the moment for moment1 and add in 'N' months.
moment1.endOf('month').add(N, 'months');
Finally, do your comparison.
moment2.isAfter(moment1);
I'm not sure how to get that string representation of the ISODate object, perhaps just .toString().
However, this is how you can get the time difference in months with the myCol.createdAt represented by the current date Date.now().
var isoString = "2017-02-09T01:22:30.894Z"
var today = Date.now()
console.log(moment(isoString).diff(today, 'months'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.0/moment.min.js"></script>
I need to get the difference (in minutes) from a datetime that I get froma get request in a string format to now.
According to my research, I can use moment.js to do so, but I haven't figured out now.
That format I am getting the date/time to be compared is as:
2017-02-10T20:52:13.885Z
I have already tried to do some operations with moment.js such as
moment().startof(comparedTime).fromNow())
But it returns nothing.
What are the alternatives and the best way to do this?
Can't you just use vanilla javaScript?
var getDate = '2017-02-10T20:52:13.885Z'; //get time from server
var parseDate = new Date(getDate).getTime(); //change string into Date object into milliseconds
var nowDate = Date.now(); //get current Date in milliseconds
var minutes = Math.round((nowDate-parseDate)/1000/60); //subtract times, count seconds (/1000), count minutes (/60)
console.log(minutes);
You need to create a moment object by passing the date string in. e.g.
myDate = moment(myISOString)
https://momentjs.com/docs/#/parsing/
Then you can use the moment object as described in the docs.
With Moment.js, this is simply:
moment().diff('2017-02-10T20:52:13.885Z', 'minutes') // 65
If you want partial minutes included, then pass true as a third parameter:
moment().diff('2017-02-10T20:52:13.885Z', 'minutes', true) // 65.04565