I am working with an API that returns dates in UNIX format: i.e. 1441647410.
With the following moment.js helper, I am able to convert it to a more readable format (05/22/15, 09:33):
UI.registerHelper('formatUnix', function(context, options) {
if(context)
return moment.unix(context).format('MM/DD/YY, hh:mm');
});
Instead of displaying an absolute time, I'd like to display time elapsed from now (i.e. 5 hrs ago, or 11 weeks ago) in this example. How could I do that? I am trying to define now with moment(), but it doesn't seem to be working:
UI.registerHelper('fromNow', function(context, options) {
if(context)
var now = moment();
var diff = now - context;
return moment.unix(diff).format('hh');
});
How can I should an amount of time elapsed from now (11 weeks ago) instead of an absolute time (5/22/15)? Also, is there any way for the browser to automatically grab the client's local time?
Thanks !
What about parsing unix into moment time and then using from:
return moment(context).from(moment());
You were close, you just need to use the fromNow() method after constructing the moment instance using moment.unix():
moment.unix(context).fromNow()
Related
We escape of using moment now and use date-fns instead. In some places we still use moment on front.
Example of code on server
//date in yyyy/mm/dd format in query params
startOfDay = StartOfDay(new Date(date));
return startOfDay
And when I display this date on front, she changes to local timezone(-4 hours). If i use date-fns-tz and convert to Canada timezone, I will get date with -4 hours and after display -4 hours more. How to resole this issue? I need to add 4 hours to date for my current timeZone. My utcOffset = 4.
Although I am not sure what function your are currently using from date-fns-ts, what has worked for me is to use utcToZonedTime(). This function gets
a date/time in the local time of any time zone from UTC time
import { utcToZonedTime } from 'date-fns-tz'
const now = new Date() // UTC
const nowCustomTimeZone = utcToZonedTime(now, 'Europe/Amsterdam')
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
I am trying to understand how creation of dates using Javascript on client and server both can affect query results when timezone of client and server can differ.
On client side, I am using Date.now() to save timestamp information
var time = Date.now()
console.log(time);
The now() method returns the milliseconds elapsed since 1 January 1970
00:00:00 UTC up until now as a Number.
My understanding is that this timestamp is independent of any timezone offset, in other words it points to time at Zero timezone offset. Is it correct?.
We can also get this timestamp using the following code
var now = new Date();
time = now.getTime();
console.log(time);
This code still gives the same timestamp information (at zero timezone offset). Is Date.now() just a quick way to get timestamp?
Now, constructing date from Date.now() and displaying it in browser's console.
var time = Date.now()
console.log(time);
var date = new Date(time)
var time = date.getTime()
console.log(time);
console.log(date);
In my opinion, it is only when displaying in browser's console, date is formatted in the browser's local timezone otherwise this date instance still holds timestamp at zero timezone offset. Is it correct?.
I have also seen an answer of converting Javascript date to UTC
var now = new Date();
var now_utc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
time = now_utc.getTime();
console.log(time);
This code still gives the same timestamp information as given by Date.now() and console.log statements were differing by few milliseconds only which I think is due to code execution time instead of any timezone difference. When executed, following was the output for that instance of time:
1468408292575
1468388492000
Is there any difference between a UTC timestamp and timestamp given by Date.now()?
Can you please confirm if these three options produce same result (i.e. independent of any timezone) and if it is safe to use this timestamp information for client and server interactions when they are in a different timezone. Examples:
Client sends a save request to server side to save this client side generated timestamp?
Client asks for results based on this saved timestamp?
I want to reduce this to a level where I want to show timezone information only for display purpose e.g. in HTML, in generated files.
My questions might be too simple because I am confused on seeing the Date class documentation on correctly using it to avoid time difference issues.
both are typically same, but Date.now() is little faster
Further Reading:
Performance - Date.now() vs Date.getTime()
Performance .now() vs Date.now()
I posted an answer on date and timezone related question. Answer says that the internal recording of the date generated on client side are at zero timezone offset. Just adding answers to individual questions:
My understanding is that this timestamp is independent of any timezone
offset, in other words it points to time at Zero timezone offset. Is
it correct?.
Yes
This code still gives the same timestamp information (at zero timezone
offset). Is Date.now() just a quick way to get timestamp?
Yes
Is there any difference between a UTC timestamp and timestamp given by Date.now()?
No
I am working on a project and suddenly found an issue. Issue was, server is sending Unix timestamps which is GMT but due to daylight saving the date
was populated as GMT. It can be achievable from server end but there is very simple way where we can convert it to local-time zone(in my case GMT to BST)
Create three variables
getPerfectLocalTime
yourUnixTimestamp
yourFormat
And below is the logic, you can use
var GMTtime = moment(yourUnixTimestamp*1000).format('YYYY-MM-DD HH:mm:ss'); // It should be YYYY-MM-DD format
var convertToUtc = moment.utc(GMTtime).format('YYYY-MM-DD HH:mm:ss');
var localTimeToDate = moment.utc(convertToUtc).toDate();
var isDSTDateTime = moment(GMTtime, 'YYYY-MM-DD');
var month = isDSTTime.format('M');
var day = isDSTTime.format('D');
var year = isDSTTime.format('YYYY');
if(moment([year, month, day]).isDST()){
getPerfectLocalTime = moment(localTimeToDate).format(yourFormat);
}else {
getPerfectLocalTime = moment(yourUnixTimestamp*1000).format(yourFormat);
}
Hope it helps anyone in programming world :)
Given that the only input in your example is yourUnixTimestamp, and you are multiplying by 1000, I'll assume that this is a traditional Unix Timestamp - an integer number in terms of whole seconds since midnight 1970-01-01 UTC.
Simply call moment.unix to parse this particular kind of input value. The resulting moment object will already be in local mode, so you can just format it directly.
moment.unix(yourUnixTimestamp).format(yourFormat)
If you want to know whether or not DST is in effect in the local time zone, you can just ask for that directly too.
moment.unix(yourUnixTimestamp).isDST()
But note that you do not need to know this to format the time correctly. Moment already takes this into consideration internally.
I have tried to search for the answer already, and although I find answers that are very similar, I don't think they are exactly what I am looking for. Please forgive me if this is already answered elsewhere.
I am trying to parse an ISO date in javascript so that I can compare it to the client system date and display information depending on if the ISO date is before or after the client system date.
This was fine until I needed to support IE8 and now I am stuck.
I have created a function because I have three different dates that I need to do this to.
for example, my ISO date is: 2015-12-22T11:59 in UTC time.
but once my date is parsed, the full date is 11:59 in local time, no matter which time zone i test, it's always 11.59 in THAT time zone.
I know that the function I have created currently doesn't do anything with timezone, this is where I am stuck. I don't know what to add to get my end date to change as a reflection of the timezone of the clients machine.
any help or advice would be greatly appreciated.
I am not able to use something like moments.js because I have an upload restriction.
Jquery is available though. or plain javascript.
<script>
function setSaleContent() {
//creating a new date object that takes the clients current system time. so we can compare it to the dates stored in our array
var currentDate = new Date();
console.log(currentDate + " this is the clients date ");
//These variables actually come from an external array object, but I'm putting them in here like this for this example.
var destinations = {
freedate: "2015-12-16T11:59",
courierdate: "2015-12-22T11:59",
nextdaydate: "2015-12-23T11:59",
}
//fetch all the ISO dates from the array.
var freeDateISO = destinations["freedate"];
var courierDateISO = destinations["courierdate"];
var nextdayDateISO = destinations["nextdaydate"];
//I am creating this reusable function to split up my ISO date for the sake of IE8.. and create it into a date format that can be compared against another date. I know that this isn't doing anything with my timezone and that is where my problem lies.
function parseDate(str) {
var parts = /^(\d{4}).(\d{2}).(\d{2}).(\d{2}):(\d{2})/.exec(str);
if (parts) {
return new Date(parts[1], parts[2] - 1, parts[3], parts[4], parts[5]);
}
return new Date();
}
//I would like this date to change to reflect the time zone of the clients system time.
//currently returns the date at 11.59 regardless of timezone.
//If i was in GMT i would want it to say 11.59
//If i was in CT time I would like this to say 05.59
//If i was in Perth I would like this to say 19:59
var freeDate = parseDate(freeDateISO);
console.log(freeDate + " this is the converted date for IE")
}
window.onload = setSaleContent;
The simple solution is to append Z to the ISO date to indicate it is in UTC time, such as 2015-12-22T11:59Z.
When JavaScript parses that date as a string, it will then automatically convert the UTC date to the local time zone.
While this is simple enough with a parsing call in the form new Date(str);, it will not play nice with your parse call with numerical arguments targeting IE8 and other old browsers.
A polyfill for parsing ISO dates with timezone exists: Javascript JSON Date parse in IE7/IE8 returns NaN
This can replace your custom parseDate function after some modification to take an input string.
Alternatively, implement your own custom date manipulater to account for the local timezone using the .getTimezoneOffset() method on the newly created date, which gives the time zone offset in minutes, but you will have to come up with a method of utilising the offset such as adjusting hours and minutes, due to the limited methods of the JavaScript date object.