momentjs override the default global date for today - javascript

I'd like to set a default time for momentjs. For instance the default behavior is:
moment().format('YYYY-MM-DD') // returns current date
What I'd like to do is to override the current date to some other date, i.e. 2017-03-01, so whenever I do
moment().format('YYYY-MM-DD')
>> "2017-07-31"

The Moment.js code calls new Date() to initialize itself when the constructor is called without arguments (technically, it calls new Date(Date.now()), but the result is the same). You have to pass something to get a specific date.
Of course, you could alter your local copy of the Moment.js library, but this is not recommended. You would have to keep it up-to-date with later releases of the libraries. And causing moment() to return anything other than the current date would cause those looking back at your code to wonder what's going on.
Upon further investigation, it seems Moment.js does allow you to overwrite the implementation of moment.now() which tells the rest of the library what time it is. See this article on the Moment.js website for more. There's an example there:
moment.now = function () {
return +new Date();
}
Which would be easy to alter for your needs:
moment.now = function () {
return +new Date(2017, 2, 1); // March 1st, 2017
}
I would strongly suggest using this technique sparingly (if at all) for the reasons given in the second paragraph above.

Related

How to check Daylight Saving Time with Temporal in Javascript?

In case I have a Date and I want to check if the time is DST I can use a method, such as the following:
function isDST(d) {
let jan = new Date(d.getFullYear(), 0, 1).getTimezoneOffset();
let jul = new Date(d.getFullYear(), 6, 1).getTimezoneOffset();
return Math.max(jan, jul) != d.getTimezoneOffset();
}
(source here)
In case I use MomentJS library I reach the same in this way:
moment().isDST();
Anyone knows how to do the same with the upcoming Temporal?
I'd recommend not doing this, at least not in this form.
Aside from the Ireland example mentioned in the comment, there are other time zone jurisdictions where there are one-time or non-semiannual changes in the offset from UTC that occurred for other reasons than DST, and any possible isDST() implementation will, by definition, malfunction in these cases. Another example is that Morocco observes year-round DST except during the month of Ramadan. For most of the world's population, "DST" has no meaning at all.
To solve this, I'd start by asking what you are going to use the information for?
If it's, for example, to specify "Daylight" or "Standard" time in the name of a time zone, you could instead use Intl.DateTimeFormat with the { timeZoneName: 'long' } option, which will give you the name of the time zone with this information included.
If you need it as a drop-in replacement for Moment's isDST() method so that you can port an existing system from Moment to Temporal, I'd recommend reimplementing the Moment function exactly, and plan to move away from the concept of "is DST" in the future. (Note, that the Moment documentation also describes this function as a hack that sometimes doesn't provide correct information.)
The body of the Moment function can be found here and the equivalent for Temporal would be:
function isDST(zdt) {
return (
zdt.offsetNanoseconds > zdt.with({ month: 1 }).offsetNanoseconds ||
zdt.offsetNanoseconds > zst.with({ month: 6 }).offsetNanoseconds
);
}
Another thing that you might need this information for is to interface with other systems that include an "is DST" bit in their data model (which is an incorrect concept, but you might have no choice.) In this case I'd recommend restricting the "is DST" function to a list of allowed time zones that are known to employ the concept of "DST" and returning false in other cases, which should at least filter out some of the false positives.
if (!listOfTimeZoneIDsWithDST.includes(zdt.timeZone.id))
return false;
the temporal api has a offsetNanoseconds read-only property
zdt = Temporal.ZonedDateTime.from('2020-11-01T01:30-07:00[America/Los_Angeles]');
zdt.offsetNanoseconds;
// => -25200000000000
also there's the with method which returns a new object with specified field being overwritten.
i have to admit i haven't tested it but something like this should basically be the equivalent to your function. (month index starts at 1)
function isDST(d) {
let jan = d.with({month: 1}).offsetNanoseconds ;
let jul = d.with({month: 7}).offsetNanoseconds ;
return Math.min(jan, jul) != d.offsetNanoseconds ;
}
zoned DateTime
refine dev
web dev simplified

moment.js mock local() so unit test runs consistently

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;
});

How to detect changes with Date objects in Angular2?

Date objects that are modified using setDate method arent getting updated in template.
In template:
<p>{{date | date:'mediumDate'}}</p>
In component:
nextDay(){
this.date.setDate(this.date.getDate()+1);
}
But when I call nextDay function, the template isnt updated with the new value.
The only way I could get the change detection working was doing this:
nextDay(){
var tomorrow = new Date();
tomorrow.setDate(this.date.getDate()+1);
this.date = tomorrow;
}
Are there a better way to accomplish this same task?
I think that is the right way, to change the reference of the date variable. From the docs here we have:
The default change detection algorithm looks for differences by comparing bound-property values by reference across change detection runs.
So if the date reference remains the same, nothing will happen. You need a new Date reference and that's why the second version of nextDay() works.
If you remove the formatting pipe you will see that still only the second version of nextDay() works.

How do i use a for loop to loop every argument into newDate?

I have a timeMachine function that takes in 5 parameters and tells you what day it is after the time you entered. But instead of writing newDate.setDate(dateObject.getDate()+daysLater); i want to use a for loop that loops over the arguments' length and logs the inputs into newDate.
var timeMachine=function(yearsLater,monthsLater,daysLater,hoursLater,minutesLater) {
var dateObject=new Date();
var newDate=new Date();
newDate.setDate(dateObject.getDate()+daysLater);
newDate.setMonth(dateObject.getMonth()+monthsLater);
newDate.setYear(dateObject.getFullYear()+yearsLater);
newDate.setHours(dateObject.getHours()+hoursLater);
newDate.setMinutes(dateObject.getMinutes()+minutesLater);
console.log(newDate);
}
timeMachine()
This isn't using a for loop, but I'd suggest using MomentJS for any date-based manipulation. Speaking from personal experience, time manipulation is easy to mess up.
Moment already has this sort of "timeMachine()" functionality built in. For instance:
var futureMoment = moment()
.add(yearsLater, 'years')
.add(monthsLater, 'months')
.add(daysLater, 'days')
.add(hoursLater, 'hours')
.add(minutesLater, 'minutes');
console.log(futureMoment.format()); // <<== get a formatted string
console.log(futureMoment.toDate()); // <<== 'toDate' gets the native Date object
It also has copious documentation, and good plugins for added functionality. If you add moment-parseformat, you can easily parse most real-world Date strings (i.e. "November 20th, 2015" or "11/20/15" or "2015/11/20", etc) into Moment objects.
Basically, don't do this yourself unless you really need the bare bones functionality. Standing on the shoulders of giants is much easier.

How to set angular moment timezone globally?

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');
}
]);

Categories

Resources