简体   繁体   English

如何从JavaScript应用程序将Instant传递给spring-data-rest API

[英]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: 我有一个spring-data-rest API,我创建了一个查询,如下所示:

@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. 其中Transaction.transactionDate是即时类型。 how I should pass a date from a javascript app? 我应该如何通过javascript应用传递日期?

Typically timestamps are stored/transferred/etc. 通常,时间戳是存储/传输/等。 in one of two ways: 通过以下两种方式之一:

UNIX timestamps UNIX时间戳

This is just a number representing the number of seconds from a fixed time in the past (known as the UNIX epoch ). 这只是一个数字,表示从过去的固定时间起的秒数(称为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. Java具有Instant#getEpochSecond()方法来获取此值,以及Instant.ofEpochSecond()静态方法来根据时间戳创建Instant对象。

Javascript has the Date type which can be instantiated from a timestamp ( new Date(timestamp * 1000) ), and transformed into a timestamp with difficulty . Javascript具有Date类型,该类型可以从时间戳( new Date(timestamp * 1000) )实例化,并很难转换为时间戳。

ISO 8601 strings ISO 8601字符串

This is just regular ASCII text with a standardised format, for example: 这只是具有标准化格式的常规ASCII文本,例如:

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: Java使用Instant#toString()来获取ISO 8601字符串,此稍微冗长的方法可以转换回来:

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() . Javascript不支持时区,但仍可以使用Date#toISOString()生成符合ISO的字符串,并使用静态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. 无论您采用哪种方式,如果这对您来说很重要,您都可能希望在javascript端使用其他库来更好地控制时间戳。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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