To compare two dates with date-fns, all you need to do is to import the functions, isAfter, isBefore, or areEqual to get the same functionality as above. Unlike something like moment.js (which is to be avoided), date-fns uses the native JavaScript Date object so you don’t have to worry about having a large overhead in the size of the library.Īlso, date-fns is simply a collection of utilities and helper methods to make using native JavaScript Date objects much easier, similar to what we did above. One of the best JavaScript date libraries out there for this problem is called date-fns. This is where a good, lightweight library could save you a lot of time, and headaches. This is great if you are wanting your comparisons to be as lightweight as possible, but the problem is that it can be pretty time consuming to have to write out and test all the helper methods you might need to compare and work with JavaScript dates. These methods of comparing dates will work for the current time, preset times and times in any format (e.g mm/dd/yyyy) as long as they have been created as a native JavaScript Date. How can we improve comparing two dates in JavaScript with a library getTime ( )īy splitting these out into individual functions it makes it easier to read, use and maintain in the future and we now get the added benefit of dealing with booleans rather than numbers. getTime ( ) const dateIsBefore = ( dateA, dateB ) => getDateAsDay (dateA ). getTime ( ) const dateIsAfter = ( dateA, dateB ) => getDateAsDay (dateA ). getDay ( ) ) const datesAreEqual = ( dateA, dateB ) => getDateAsDay (dateA ). Whilst this is fine in this case, it would be better to split this up into multiple, more verbose, helper functions to avoid confusion, we can do this like so:Ĭonst getDateAsDay = someDate => new Date (someDate. The last part to look at with this helper function is that it will return 0 if the dates are equal, 1 if the first date is larger than the second date, and -1 if the first date is less than the second date. With months for example, you would only need to pass in years and months, whereas for years you would only need to pass in years, but for hours you would need to pass in the years, months, days and hours. To compare seconds, hours, months or years it is the exact same principle but you just need to pass in whichever is relevant into the Date constructor for your needs. In this helper function we create two new dates and we only set the years, months and days, and not the hours, minutes, seconds and milliseconds.īy doing that we can compare only the days without the time. Comparing dates is something that can be a little confusing in JavaScript because you can’t just compare two Date objects because they are objects and as well all know
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |