8/7/2023 0 Comments Moment js local![]() ![]() That way, we will get 3 unique moment objects and their respective datetime values.įor backend applications, it is pretty common to validate that the properties found in the request body are the specified type that we expect them to be. ![]() ![]() const today = moment()Ĭonst oneWeekLater = today.clone().add( 1, "week")Ĭonst twoWeeksLater = today.clone().add( 2, "week") Hence, the solution to this problem is rather straight forward - we simply have to clone the moment object before performing arithmetic operations. add, moment mutates the original object rather than mutating a copy of that object. This is because it turns out that all 3 constants refer to the same moment object, with the same datetime value. However, when we log the 3 values, it turns out that they all have the same date. const today = moment()Ĭonst oneWeekLater = today.add( 1, "week")Ĭonst twoWeeksLater = today.add( 2, "week") ![]() Instead of constantly writing hard coded values like “”, “”, I could create relative moment objects for testing. In many DateTime manipulation test cases, we would want to create DateTime objects in a chronological order. Otherwise you can refer to the source code found here at this GitHub repository on how Jest can be setup for a simple Node.js project. If you are not familiar with Jest or find it a bother to set it up, you can also simply console.log the relevant variables to check the values manually. There will also be Jest tests in the article to illustrate that the functionalities work as intended. Some examples given here are inspired based on what I have done at work. And for those who don’t have to, this article also serves as an interesting read for those who are curious about problems that can come from Moment.js & working with DateTime. Hence, this article is meant to highlight some strange gotchas for anyone who still has to deal with Moment.js. Nonetheless, there are many developers who still have to work with this library because many existing production projects use it heavily, and it take significant effort to do a code revamp to migrate to use another immutable datetime library. Even the library maintainers themselves discourage you to use Moment.js in new projects going forward.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |