简体   繁体   中英

How to pass an Instant from a javascript app to a spring-data-rest API

I have a spring-data-rest API and I create a query like so:

@Query("SELECT at FROM Transaction at WHERE at.transactionDate BETWEEN :start AND :end")
Page<AssetsTransaction> findAllByDates(
    @Param("start") Instant start,
    @Param("end") Instant end,
    Pageable pageable);

Where Transaction.transactionDate is an Instant type. how I should pass a date from a javascript app?

Typically timestamps are stored/transferred/etc. in one of two ways:

UNIX timestamps

This is just a number representing the number of seconds from a fixed time in the past (known as the UNIX epoch ).

Java has the Instant#getEpochSecond() method to obtain this value, and the Instant.ofEpochSecond() static method to create an Instant object from a timestamp.

Javascript has the Date type which can be instantiated from a timestamp ( new Date(timestamp * 1000) ), and transformed into a timestamp with difficulty .

ISO 8601 strings

This is just regular ASCII text with a standardised format, for example:

2018-11-21T22:25:58+00:00

You gain the advantage of timezone support with this method.

Java uses Instant#toString() to get an ISO 8601 string, and this slightly more verbose method to convert back:

Instant.from(DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse(string));

Javascript does not have native support for timezones, but it can still produce an ISO-compliant string with Date#toISOString() and parse it back with the static Date.parse() .

Whichever way you go, you may wish to use an additional library on the javascript side to gain more control over your timestamps, if this is important to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM