将时间从特定时区转换为UTC(ColdFusion/Java)

发布于 2025-02-11 15:36:08 字数 784 浏览 2 评论 0原文

我们需要采用DateTime字符串(我们已经从用户表输入中收到并验证了它),将其视为特定于America/new_york时区,然后将其转换为utc < /代码>。

我们目前正在运行ColdFusion 2018,其本机DateTime功能受到限制。所以我想利用基础的爪哇。大多数与CF相关的解决方案都是Java.Time,因此我根据其他堆栈溢出答案尝试了自己的尝试。希望拥有更多Java知识的人可以审查此解决方案。 (这是在CF脚本中,但应该是非常自我记载的。)这是正确的,是否有更好/更有效的解决方案?

var validatedDateTime = '2022-06-29T14:30:00';

LocalDateTime = createObject('java', 'java.time.LocalDateTime');
ZoneID = createObject('java', 'java.time.ZoneId');
ZoneOffset = createObject('java', 'java.time.ZoneOffset');

ldt = LocalDateTime.parse(validatedDateTime);
nyZone = ZoneID.of('America/New_York');
odt = ldt.atOffset(nyZone.getRules().getOffset(ldt));
utcDateTime = odt.withOffsetSameInstant(ZoneOffset.UTC).toLocalDateTime();```

We need to take a datetime string (which we've already received and validated from user form inputs), treat it as being specific to the America/New_York timezone, and convert it to UTC.

We're currently running ColdFusion 2018, which is limited in its native datetime functionality. So I wanted to tap into the underlying Java. Most CF-related solutions are pre-java.time, so I attempted my own based on other Stack Overflow answers. Hoping someone with more Java knowledge can review this solution. (This is in CF Script, but it should be pretty self-documenting.) Is this correct and is there a better/more efficient solution?

var validatedDateTime = '2022-06-29T14:30:00';

LocalDateTime = createObject('java', 'java.time.LocalDateTime');
ZoneID = createObject('java', 'java.time.ZoneId');
ZoneOffset = createObject('java', 'java.time.ZoneOffset');

ldt = LocalDateTime.parse(validatedDateTime);
nyZone = ZoneID.of('America/New_York');
odt = ldt.atOffset(nyZone.getRules().getOffset(ldt));
utcDateTime = odt.withOffsetSameInstant(ZoneOffset.UTC).toLocalDateTime();```

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

纵性 2025-02-18 15:36:08

tl;

您说:

问题更多是关于拿到DateTime字符串(例如2022-06-29T14:30:00'),将America/New_york TimeZone添加到它,然后将其转换为UTC。

LocalDateTime
.parse( "2022-06-29T14:30:00" )      // “taking a datetime string (e.g. '2022-06-29T14:30:00')”
.atZone( 
    ZoneId.of( "America/New_York" )  // “adding the America/New_York timezone to it”
)                                    // Returns a `ZonedDateTime` object. 
.toInstant()                         // “converting it to UTC”

请参阅此 code在indeone.com 中实时运行。

2022-06-29T18:30:00z

详细信息

您忽略了提及数据库引擎和列的精确类型。因此,我们无法给出完整的答案。我可以解决其中的一部分。

因此,目标是获取用户的日期&amp;时间,像美国/new_york一样对待它,然后将其转换为UTC。

DateTimeFormatter fDate = DateTimeFormatter. … ;  // Define a formatter to match the format used by your user. 
LocalDate ld = LocalDate.parse( inputDate , fDate ) ;

dateTimeParseException的陷阱以检测故障输入。

对于localtime,类似地执行操作。

DateTimeFormatter fTime = DateTimeFormatter. … ;  // Define a formatter to match the format used by your user. 
LocalTime lt = LocalDate.parse( inputTime , fTime ) ;

与时区结合在一起以确定瞬间。

ZoneId z = ZoneId.of( "America/New_York" ) ;
ZonedDateTime zdt =
ZonedDateTime.of( ld , lt , z ) ;

调整到UTC。

Instant instant = zdt.toInstant() ;

在堆栈溢出上,所有这些都被覆盖了很多次。搜索以了解更多。

tl;dr

You said:

The question is more about taking a datetime string (e.g. '2022-06-29T14:30:00'), adding the America/New_York timezone to it, and converting it to UTC.

LocalDateTime
.parse( "2022-06-29T14:30:00" )      // “taking a datetime string (e.g. '2022-06-29T14:30:00')”
.atZone( 
    ZoneId.of( "America/New_York" )  // “adding the America/New_York timezone to it”
)                                    // Returns a `ZonedDateTime` object. 
.toInstant()                         // “converting it to UTC”

See this code run live at Ideone.com.

2022-06-29T18:30:00Z

Details

You neglected to mention your database engine and the precise type of your column. So we cannot give a full answer. I can address part of it.

So the goal is to take the user's date & time, treat it like America/New_York, and convert it to UTC.

DateTimeFormatter fDate = DateTimeFormatter. … ;  // Define a formatter to match the format used by your user. 
LocalDate ld = LocalDate.parse( inputDate , fDate ) ;

Trap for DateTimeParseException to detect faulty inputs.

Do similarly for LocalTime.

DateTimeFormatter fTime = DateTimeFormatter. … ;  // Define a formatter to match the format used by your user. 
LocalTime lt = LocalDate.parse( inputTime , fTime ) ;

Combine with time zone to determine a moment.

ZoneId z = ZoneId.of( "America/New_York" ) ;
ZonedDateTime zdt =
ZonedDateTime.of( ld , lt , z ) ;

Adjust to UTC.

Instant instant = zdt.toInstant() ;

All of this has been covered many many times on Stack Overflow. Search to learn more.

过气美图社 2025-02-18 15:36:08

这是我要做的:

喜欢您,我将时间戳存储在UTC中。然后,我将它们输入包裹在元素中的ISO-8601格式中,以便然后使用任意数量的JavaScript库在浏览器中转换它们。我使用 sugar.js ,我喜欢。

这样做的优点是,由于时间戳是在浏览器中渲染的,因此它将使用该计算机上设置的当前时间和时区。结果是,无论是什么时区,时间戳都将在本地渲染。

例如,在ColdFusion的服务器上,以下代码将您的本地服务器时间转换为UTC。即使您的服务器在UTC中,我认为您应该这样做,以始终确定。

utc = DateConvert(“Local2UTC”, now());

然后,在ISO中输出DOM中的日期:

writeOutput('<span class="isodate">#DateFormat(utc, "YYYY-MM-DD")#T#TimeFormat(utc, "HH:mm:ss.l")#Z</span>');

浏览器将获得:

<span class="isodate">2022-06-29 15:00:00.000Z</span>

然后编写一些JavaScript代码以找到这些同义词元素并将其转换。在Sugar.js中,它看起来像(我正在使用jQuery只是为了使其易于理解):

$('span.isodate').each(function(ix,elem) {
    var iso = $(elem).text(),
        d = Date.create(iso),
        localDate = d.format('{Weekday}, {Month} {d}, {yyyy} at {h}:{mm} {tt} (' + d.relative() + ')');
    $(elem).text(localDate);
});

当然,您可以使用所需的任何格式,或者您想转换日期的任何JavaScript库。 mommsjs.com 是另一个,但更复杂。 Sugar.js非常轻巧且易于使用,并且具有良好的日期支持。

上面的这些代码片段演示了难题的部分,尚未进行测试。您可以随心所欲地使其所有工作...我还拥有JavaScript功能,可以轻松找到并将这些元素转换为本地时间。祝你好运!

Here’s what I do:

Like you, I store timestamps in UTC. Then I output them into the DOM in ISO-8601 format wrapped in a element so I can then find them and and convert them in the browser using any number of JavaScript libraries. I use sugar.js, which I love.

The advantage to doing it this way is that because the timestamp is rendered in the browser, it will use the current time and time zone that is set on that computer. The result is that the timestamp will be rendered locally no matter what timezone they are in.

For example, on the server in ColdFusion, the following code converts your local server time to UTC. Even if your server is in UTC, I think you should do this just to always be sure.

utc = DateConvert(“Local2UTC”, now());

Then, output the date in ISO where it goes in the DOM:

writeOutput('<span class="isodate">#DateFormat(utc, "YYYY-MM-DD")#T#TimeFormat(utc, "HH:mm:ss.l")#Z</span>');

The browser will get:

<span class="isodate">2022-06-29 15:00:00.000Z</span>

Then write some JavaScript code to find those isodate elements and convert them. In sugar.js it looks something like (I'm using jquery just to make it easy to understand):

$('span.isodate').each(function(ix,elem) {
    var iso = $(elem).text(),
        d = Date.create(iso),
        localDate = d.format('{Weekday}, {Month} {d}, {yyyy} at {h}:{mm} {tt} (' + d.relative() + ')');
    $(elem).text(localDate);
});

Of course you can use whatever format you want, or whatever Javascript library you want to convert the date. momentjs.com is another one, but a little more complex. Sugar.js is super lightweight and easy to use and has great date support.

These code snippets above demonstrate the pieces of the puzzle and have not been tested. You could make it all work however you want... for example, I have a ColdFusion function that generates an ISO-8601 string for given a date. I've also got javascript functions that make it easy to find and convert these elements to local time. Good luck!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文