用于不同时区的Javascript DateFormat [英] Javascript DateFormat for different timezones

查看:124
本文介绍了用于不同时区的Javascript DateFormat的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名Java开发人员,我习惯使用SimpleDateFormat类,它允许我通过设置时区将任何日期格式化为任何格式。

I'm a Java developer and I'm used to the SimpleDateFormat class that allows me to format any date to any format by settings a timezone.

Date date = new Date();

SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");

sdf.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
System.out.println(sdf.format(date)); // Prints date in Los Angeles

sdf.setTimeZone(TimeZone.getTimeZone("America/Chicago"));
System.out.println(sdf.format(date)); // Prints same date in Chicago

SimpleDateFormat是一个非常简洁的Java解决方案但不幸的是我不能在Javascript中找到任何类似的替代方案。

SimpleDateFormat is a pretty neat solution in Java but unfortunately I can't find any similar alternative in Javascript.

我正在 Javascript 中扩展Date原型以完全相同。我有Unix格式的日期,但我想在不同的时区格式化它们。

I'm extending the Date prototype in Javascript to do exactly the same. I have dates in Unix format but I want to format them in different timezones.

Date.prototype.format = function(format, timezone) {
    // Now what?
    return formattedDate;
}

我正在寻找一种巧妙的方法来做到这一点,而不是黑客。

I'm looking for a neat way to do this rather than a hack.

谢谢

推荐答案

JavaScript没有内置支持其他时区比本地时区。您只能以当地时间或UTC时间表示日期。无法更改Date对象的时区偏移量。

JavaScript does not have build in support for other time zone than the local one. You can only express a date in local time or in UTC time. There is no way to change the time zone offset of a Date object.

因此,没有整洁的方法来解决您的问题。

Thus, there is no "neat" way to solve your problem.

这篇关于用于不同时区的Javascript DateFormat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆