I have a moment object like below
from which i want to extract the time zone value "PDT".
How can i get this value using moment?
i have tried
moment.tz(this.startDate.toString()).zoneAbbr();
but that returns a value "UTC"
Any suggestions?
I am Afraid you will get this only..
Since this is how the getZoneAbbr function works.
function getZoneAbbr () {
return this._isUTC ? 'UTC' : '';
}
Now, This is a problem. UTC is what one can use with timeOffest to determine which TimeZone you are lying in.
and only way to do it to make a list of Time zone names with their offset values, then compare which offset value you get.
then you can pick your time zone.
Even the normal JavaScript Date function do not have this support as in yet. you will have to create that offset and time zone name map yourself.
You might wan't to add the specific timezone you're in for the date that you parse like following:
moment.tz(moment.now(), 'America/New_York').zoneAbbr();
Moment had the z / zz format parameter to get abbreviated time zone name, but as the doc says:
Note: as of 1.6.0, the z/zz format tokens have been deprecated from plain moment objects. Read more about it here. However, they do work if you are using a specific time zone with the moment-timezone addon.
In the linked github issue, moment developer suggest to use moment.tz.guess() when creating moment object to have good chances of getting enviroment's timezone.
Here a working code example that you can use to get abbreviated time zone name:
var startDate = new Date();
var momObj = moment.tz(startDate, moment.tz.guess());
var zoneAbbr1 = momObj.zoneAbbr();
console.log(zoneAbbr1);
var zoneAbbr2 = momObj.format('z')
console.log(zoneAbbr2);
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.5/moment-timezone-with-data-2010-2020.min.js"></script>
Make sure you have installed moment-timezone with
npm install moment-timezone --save
After that
var moment1 = require('moment-timezone');
var myTime = moment1.tz('America/Denver').format('YYYY-MM-DD HH:mm:ss');
console.log(myTime);
Related
I am use moment library for getting time zone
moment.tz.guess()
which is returning 'Asia/Calcutta' (old name), instead of that I want the latest name which is 'Asia/Kolkata' (new name).
Or any other way to get this new name time zone.
As Felix suggested, just make the replacement on your end:
let timezoneGuess = moment.tz.guess();
timezoneGuess = timezoneGuess.replace("Calcutta","Kolkata");
This code tries to find "Calcutta" in the timezone name and, if it's there, replaces it with "Kolkata."
I've got a javascript app that the user insists that regardless of location of the app user, they want date/times entered by the user in Eastern time. That they will be sent to the database and stored, and later displayed again in the app and displayed in Eastern timezone.
So I was looking to use moment.js and moment-timezone, but can't figure out how to make it work.
When I try const objMoment = moment(), objMoment appears to contain a time offset from the current time.
I was wanting to get a moment object that is whatever time, and then objMoment.tz("America/New_York")
but I ended up with a time that is 5 hours off from what it should be.
const objMoment = moment();
const objEastern = objMoment.clone().tz("America/New_York");
debugger;
formData.SwoDate = objMoment.toDate();
debugger;
A few things:
You don't need to create a local moment and clone it. You can instead construct a moment directly in a specific time zone with:
moment.tz('America/New_York')
Since you call toDate(), the result is always going to be a Date object that represents "now". It doesn't matter if that comes from a Moment that's been set to a different time zone or not. It's the same moment in time.
moment().valueOf() // 1600198416842
moment.utc().valueOf() // 1600198416842
moment.tz('America/New_York').valueOf() // 1600198416842
new Date().valueOf() // 1600198416842
Date.now() // 1600198416842
If you want to see the time in a different time zone, you would need to use a function like format instead.
moment.utc().format() // "2020-09-15T19:33:36Z"
moment.tz('America/New_York').format() // "2020-09-15T15:33:36-04:00"
Moment is a legacy library. You should probably choose a different library, or perhaps no library at all. Please read: Moment Project Status
I want to test the following piece of code. I am wondering if there is a way to mock moment.js or force it to think my current location is America/New_York so that my unit test doesn't fail in gitlab.ci runner which may be in various geographical locations?
const centralTimeStartOfDay = moment.tz('America/Chicago').startOf('day');
const startHour = centralTimeStartOfDay
.hour(7)
.local()
.hour();
Basically I want to hard code my timezone to be America/New_York and want this function to behave consistently.
Edit:
I tried:
Date.now = () => new Date("2020-06-21T12:21:27-04:00")
moment.tz.setDefault('America/New_York')
And still, I get the same result. I want to mock the current time so startHour returns a consistent value.
The problem
So there is no one line answer to this question. The problem is a fundamental one to javascript, where you can see dates in one of two ways:
UTC (getUTCHours(), getUTCMinutes() etc.)
local (i.e. system, getHours(), getMinutes() etc.)
And there is no specified way to set the effective system timezone, or even the UTC offset for that matter.
(Scan through the mdn Date reference or checkout the spec to get a feeling for just how unhelpful this all is.)
"But wait!" we cry, "isn't that why moment-timezone exists??"
Not exactly. moment and moment-timezone give much better / easier control over managing times in javascript, but even they have no way to know what the local timezone Date is using, and use other mechanisms to learn that. And this is a problem as follows.
Once you've got your head round the code you'll see that the moment .local() method (prototype declaration and implementation of setOffsetToLocal) of moment effectively does the following:
sets the UTC offset of the moment to 0
disables "UTC mode" by setting _isUTC to false.
The effect of disabling "UTC mode" is to mean that the majority of accessor methods are forwarded to the underlying Date object. E.g. .hours() eventually calls moment/get-set.js get() which looks like this:
export function get(mom, unit) {
return mom.isValid()
? mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]()
: NaN;
}
_d is the Date object that the moment (mom) is wrapping. So effectively for a non-UTC mode moment, moment.hours() is a passthrough to Date.prototype.getHours(). It doesn't matter what you've set with moment.tz.setDefault(), or if you've overridden Date.now(). Neither of those things are used.
Another thing...
You said:
Basically I want to hard code my time to be America/New_York and want this function behaves consistently
But actually, that is not generally possible. You are using Chicago, which I imagine has offset shifts in sync with New York, but e.g. the UK shifts at a different time from the US, so there are going to be weeks in the year where your test would fail if you were converting from a US timezone to a UK timezone.
The solutions.
But this is still frustrating, because I don't want my devs in Poland and the west coast of America to have breaking local tests because my CI server is running in UTC. So what can we do about it?
The first solution is a not-a-solution: find a different way of doing the thing you're doing! Generally the use cases for using .local() are quite limited, and are to display to a user the time in their current offset. It's not even their timezone because the local Date methods will only look at the current offset. So most of the time you'd only want to use it for the current time, or if you don't mind if it's wrong for half of the Date objects you use it for (for timezones using daylight savings). It could well be better to learn the timezone the user wants through other means, and not use .local() at all.
The second solution is also a not-a-solution: don't worry about your tests so much! The main thing with displaying a local time is that it works, you don't really care what it is exactly. Verify manually that it's displaying the correct time, and in your tests just verify that it returns a reasonable looking thing, without checking the specific time.
If you still want to proceed, this last solution at least makes your case work and a few others, and it's obvious what you need to do if you find you need to extend it. However, it's a complicated area and I make no guarantees that this will not have some unintended side-effects!
In your test setup file:
[
'Date',
'Day',
'FullYear',
'Hours',
'Minutes',
'Month',
'Seconds',
].forEach(
(prop) => {
Date.prototype[`get${prop}`] = function () {
return new Date(
this.getTime()
+ moment(this.getTime()).utcOffset() * 60000
)[`getUTC${prop}`]();
};
}
);
You should now be able to use moment.tz.setDefault() and using .local() should allow you to access the properties of the datetime as though it thought the local timezone was as configured in moment-timezone.
I thought about trying to patch moment instead, but it is a much more complicated beast than Date, and patching Date should be robust since it is the primitive.
try
// package.json
{
"scripts": {
"test": "TZ=EST jest"
}
}
Brilliant daphtdazz - thank you! To clarify for those who follow, this is the full solution I used to control the current date, timezone, and with daphtdazz's help - the local() behavior in moment:
import MockDate from 'mockdate';
const date = new Date('2000-01-01T02:00:00.000+02:00');
MockDate.set(date);
[
'Date',
'Day',
'FullYear',
'Hours',
'Minutes',
'Month',
'Seconds',
].forEach(
(prop) => {
Date.prototype[`get${prop}`] = function () {
return new Date(
this.getTime()
+ moment(this.getTime()).utcOffset() * 60000
)[`getUTC${prop}`]();
};
}
);
const moment = require.requireActual('moment-timezone');
jest.doMock('moment', () => {
moment.tz.setDefault('Africa/Maputo');
return moment;
});
I want to save the actual date in a variable. only the date, no time
var a = #Date(#Now());
datasource.replaceItemValue("variable", a)`
And
var a = #Date(#Now());
var b = new Date(a.getYear(), a.getMonth(), a.getDay());
datasource.replaceItemValue("variable", b)
Are returning 28.10.14 00:00
var dt:NotesDateTime = #Date(#Now());
datasource.replaceItemValue("variable", dt.getDateOnly());
Is throwing me an error
Isn't there a simple way to get only the actual date without the time?
Use setAnyTime() metohd of NotesDateTime class to remove time component.
If you want to save only the date use a textfield and convert the text to date, if you need it in your code
#Now uses a java.util.Date, which includes time portions. .getDateOnly() is probably throwing an error because that returns a String.
The underlying session.createDateTime() method accepts either text, a java.util.Date or a java.util.Calendar. I think all of them need to include a time element.
If you're only storing the value for reference, I'd agree with brso05 to not worry.
If you're ever likely to use #Adjust (or an equivalent), then not worrying about the time is a recipe for disaster, because every time you try to adjust, you need to remember to take into account Daylight Savings Time.
One option is to set the time to 12:00 midday. That means DST will not be a problem.
java.sql.Date is specifically designed to only include the Date portion, without a time element. Jesse Gallagher talks about java.sql.Date in the context of his frostillic.us framework https://frostillic.us/f.nsf/posts/32A63DD640D868D885257D18006659A9 and he was the one I found out about java.sql.Date from. I'm not sure how he stores those values though.
I'm not sure if the OpenNTF Domino API will allow you to just pass a java.sql.Date to a field and so store just the date portion.
I used angular moment js on my angular app. I want to show date and time according to the time zone of the current user. I'm unable to apply time zone globally on my app.
https://github.com/urish/angular-moment
I tried this.
angular.module('myapp').constant('angularMomentConfig', {
timezone: 'Europe/London' // e.g. 'Europe/London'
});
In one of my view -
{{home.eventStart| amDateFormat:'dddd, MMMM Do YYYY, h:mm:ss a'}}
In one of my controller -
$scope.profile.eventStart = moment(data.start).format('YYYY-MM-DD hh:mm a');
I'm not getting any changes in both cases, even after I set the time zone. Am I missing something ?
You cannot change constant after you set it. As injections are not dependent on module.constant or module value, this should do the trick:
angular.module('myapp').value('angularMomentConfig', {
timezone: 'Europe/London' // e.g. 'Europe/London'
});
The timezone parameter is optional. If you omit it, it will use the time zone of the local machine automatically. That is the default behavior of moment.js and of the JavaScript Date object.
I too had the same problem.
This is how to solve this out.
You need to include moment-timezone.js v0.3.0 or greater in your project, otherwise the custom timezone functionality will not be available.
Documentation here
Since version 1.0.0-beta.1, time zone can be set using amMoment service. Just inject the amMoment service and call changeTimeZone:
amMoment.changeTimezone('Europe/London');
app.run(['amMoment',
function (amMoment) {
amMoment.changeTimezone('Europe/Paris');
}
]);