The best library for XP is out in verison 1.1.0!

Time Library is out in version 1.1.0 1.2.1!

:warning: Stop the pain of the performance issues and hassle of using npm-libraries like date-fns, Moment.js or Day.js in XP! There is a better way!

Did you know that you that there is awesome functionality for working with date and time built into Java? And that those classes can be accessed in XP with this one-liner:

const ZonedDateTime = Java.type("java.time.ZonedDateTime");

No? Well… Do I have good news for you!

We have created TypeScript-types for much of the java.time namespace, making it super easy to work with dates and time on the XP-platform! So now you can do this:

import { ZonedDateTime } from "/lib/time";

const date = ZonedDateTime.parse("2023-02-21T12:15:30+01:00");
const fiftyMinutesAgo = date.minusMinutes(50);
const time = fiftyMinutesAgo.toLocalTime();
// time = "11:25:30"

:information_source: Tip: If you are migrating from one of the npm-libraries to lib-time, you might need to change the formatting strings. There is a difference on how "d" and "D" are interpreted in java.time.format.DateTimeFormatter compared to the npm-libraries.

– Tom Arild

2 Likes

Ah, timezones… the world’s best edge case simulator! :grin:
Thanks for making this library!

1 Like

PROTIP: If you are using serverside templating, you can pass temporal-objects straight into your template.

In Freemarker you can operate on a java.time.ZonedDateTime (or java.time.LocalDateTime) like this:

[#setting locale=locale]
<time datetime="${date.format('ISO_OFFSET_DATE_TIME')}">
  ${date.format('SHORT_DATE')}
</time>

Thymeleaf also has funcitonality to operate on temporals: Tutorial: Using Thymeleaf

1 Like

Another new version of lib-time is out! (1.2.1)

In version 1.2.1 I have exposed java.util.Locale.LanguageRange, which can be very useful when trying to resolve the best locale for a user – based on the Accept-Language header.

import { LanguageRange, Locale } from "/lib/time";
import { getSupportedLocales } from "/lib/xp/i18n";
import type { Request, Response } from "@enonic-types/core";

export function get(req: Request): Response {
  const languageRange = LanguageRange.parse(
    req.headers["Accept-Language"]
  );
  
  const locale: string = Locale.filterTags(
    languageRange, 
    getSupportedLocales(["i18n/phrases"])
  )[0];
  
  ...
}

Enjoy!
– Tom Arild

1 Like