将字符串转换为带时区的日期

发布于 2024-10-03 06:50:22 字数 122 浏览 0 评论 0原文

我有一个格式为 yyyy-MM-dd hh:mm a 的字符串 我可以单独获取时区对象,其中上面的字符串代表日期。

我想将其转换为以下格式。 yyyy-MM-dd HH:mm:ss Z

我该怎么做?

I have a string in the pattern yyyy-MM-dd hh:mm a
and i can get the time zone object separately in which the above string represents the date.

I want to convert this to the below format.
yyyy-MM-dd HH:mm:ss Z

How can i do this?

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

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

发布评论

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

评论(6

哑剧 2024-10-10 06:50:22

您可以将 SimpleDateFormatyyyy 一起使用-MM-dd HH:mm:ss 并显式设置 时区

public static Date getSomeDate(final String str, final TimeZone tz)
    throws ParseException {
  final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm a");
  sdf.setTimeZone(tz);
  return sdf.parse(str);
}

/**
 * @param args
 * @throws IOException
 * @throws InterruptedException
 * @throws ParseException
 */
public static void main(final String[] args) throws ParseException {
  final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
  System.out.println(sdf.format(getSomeDate(
      "2010-11-17 01:12 pm", TimeZone.getTimeZone("Europe/Berlin"))));
  System.out.println(sdf.format(getSomeDate(
      "2010-11-17 01:12 pm", TimeZone.getTimeZone("America/Chicago"))));
}

打印出:

2010-11-17 13:12:00 +0100

2010-11-17 20:12:00 +0100

2010-12-01 更新:
如果要显式打印特殊的时区,请在 SimpleDateFormat 中设置它:

sdf.setTimeZone(TimeZone .getTimeZone("IST")); 
System.out.println(sdf.format(getSomeDate(
    "2010-11-17 01:12 pm", TimeZone.getTimeZone("IST"))));

打印 2010-11-17 13:12:00 +0530

You can use SimpleDateFormat with yyyy-MM-dd HH:mm:ss and explicitly set the TimeZone:

public static Date getSomeDate(final String str, final TimeZone tz)
    throws ParseException {
  final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm a");
  sdf.setTimeZone(tz);
  return sdf.parse(str);
}

/**
 * @param args
 * @throws IOException
 * @throws InterruptedException
 * @throws ParseException
 */
public static void main(final String[] args) throws ParseException {
  final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
  System.out.println(sdf.format(getSomeDate(
      "2010-11-17 01:12 pm", TimeZone.getTimeZone("Europe/Berlin"))));
  System.out.println(sdf.format(getSomeDate(
      "2010-11-17 01:12 pm", TimeZone.getTimeZone("America/Chicago"))));
}

Prints out:

2010-11-17 13:12:00 +0100

2010-11-17 20:12:00 +0100

Update 2010-12-01:
If you want to explicitly printout a special TimeZone, set it in the SimpleDateFormat:

sdf.setTimeZone(TimeZone .getTimeZone("IST")); 
System.out.println(sdf.format(getSomeDate(
    "2010-11-17 01:12 pm", TimeZone.getTimeZone("IST"))));

Which prints 2010-11-17 13:12:00 +0530

孤独陪着我 2024-10-10 06:50:22

tl;dr

LocalDateTime.parse(                        // Parse string as value without time zone and without offset-from-UTC.
    "2017-01-23 12:34 PM" , 
    DateTimeFormatter.ofPattern( "uuuu-MM-dd hh:mm a" )
)                                           // Returns a `LocalDateTime` object.
.atZone( ZoneId.of( "America/Montreal" ) )  // Assign time zone, to determine a moment. Returns a `ZonedDateTime` object.
.toInstant()                                // Adjusts from zone to UTC.
.toString()                                 // Generate string: 2017-01-23T17:34:00Z
.replace( "T" , " " )                       // Substitute SPACE for 'T' in middle.
.replace( "Z" , " Z" )                      // Insert SPACE before 'Z'.

避免遗留日期时间类

其他答案使用麻烦的旧日期时间类(DateCalendar 等),现在是遗留的,被 java 取代.时间课程。

本地日期时间

我有一个格式为 yyyy-MM-dd hh:mm a 的字符串

这样的输入字符串缺少任何与 UTC 或时区的偏移量指示。因此我们解析为 LocalDateTime

定义格式模式以将您的输入与 <代码>DateTimeFormatter对象。

String input = "2017-01-23 12:34 PM" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd hh:mm a" );
LocalDateTime ldt = LocalDateTime.parse( input , f );

ldt.toString(): 2017-01-23T12:34

请注意,LocalDateTime 不是一个特定时刻,只是关于一系列可能时刻的模糊想法。例如,法国巴黎午夜过后几分钟,加拿大蒙特利尔仍然是“昨天”。因此,如果没有时区的上下文,例如 Europe/ParisAmerica/Montreal,只是说“几分钟午夜之后”没有任何意义。

区域ID

我可以单独获取时区对象,其中上面的字符串代表日期。

时区由 ZoneId类。

大陆/地区格式指定正确的时区名称,例如 America/Montreal非洲/卡萨布兰卡,或太平洋/奥克兰。切勿使用 3-4 个字母的缩写,例如 ESTIST,因为它们不是真正的时区,不是标准化的,甚至不是唯一的( !)。

ZoneId z = ZoneId.of( "America/Montreal" );

ZonedDateTime

应用 ZoneId 来获取 ZonedDateTime 这确实是时间线上的一个点,历史上的一个特定时刻。

ZonedDateTime zdt = ldt.atZone( z );

zdt.toString(): 2017-01-23T12:34-05:00[美国/蒙特利尔]

即时

我想将其转换为以下格式。 yyyy-MM-dd HH:mm:ss Z

首先,知道 Z 文字字符是 Zulu 的缩写,表示 UTC。换句话说,offset-from-UTC 为零小时,+00:00

即时类表示 UTC 中时间轴上的时刻,分辨率为 纳秒(最多九 (9) 位小数)。

您可以从 ZonedDateTime 中提取 Instant 对象。

Instant instant = zdt.toInstant();  // Extracting the same moment but in UTC.

要生成标准 ISO 8601 格式的字符串,例如 2017-01-22T18: 21:13.354Z,调用toString。标准格式没有空格,使用 T 将年月日期与时分秒分开,并规范地附加 Z 以获得零偏移量。

String output = instant.toString();

instant.toString(): 2017-01-23T17:34:00Z

我强烈建议尽可能使用标准格式。如果您坚持按照您指定的所需格式使用空格,请在 DateTimeFormatter 对象或仅对 Instant::toString

String output = instant.toString()
                       .replace( "T" , " " )  // Substitute SPACE for T.
                       .replace( "Z" , " Z" ); // Insert SPACE before Z.

输出:2017-01-23 17:34:00 Z

尝试一下IdeOne.com 上的实时代码


关于 java.time

java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧遗留日期时间类,例如java.util.Date, 日历,& SimpleDateFormat

Joda-Time 项目,现位于 维护模式,建议迁移到 java.time 类。

要了解更多信息,请参阅 Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范为 JSR 310

从哪里获取 java.time 类?

ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是 java.time 未来可能添加的内容的试验场。您可能会在这里找到一些有用的类,例如 IntervalYearWeekYearQuarter,以及更多

tl;dr

LocalDateTime.parse(                        // Parse string as value without time zone and without offset-from-UTC.
    "2017-01-23 12:34 PM" , 
    DateTimeFormatter.ofPattern( "uuuu-MM-dd hh:mm a" )
)                                           // Returns a `LocalDateTime` object.
.atZone( ZoneId.of( "America/Montreal" ) )  // Assign time zone, to determine a moment. Returns a `ZonedDateTime` object.
.toInstant()                                // Adjusts from zone to UTC.
.toString()                                 // Generate string: 2017-01-23T17:34:00Z
.replace( "T" , " " )                       // Substitute SPACE for 'T' in middle.
.replace( "Z" , " Z" )                      // Insert SPACE before 'Z'.

Avoid legacy date-time classes

The other Answers use the troublesome old date-time classes (Date, Calendar, etc.), now legacy, supplanted by the java.time classes.

LocalDateTime

I have a string in the pattern yyyy-MM-dd hh:mm a

Such an input string lacks any indication of offset-from-UTC or time zone. So we parse as a LocalDateTime.

Define a formatting pattern to match your input with a DateTimeFormatter object.

String input = "2017-01-23 12:34 PM" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd hh:mm a" );
LocalDateTime ldt = LocalDateTime.parse( input , f );

ldt.toString(): 2017-01-23T12:34

Note that a LocalDateTime is not a specific moment, only a vague idea about a range of possible moments. For example, a few minutes after midnight in Paris France is still “yesterday” in Montréal Canada. So without the context of a time zone such as Europe/Paris or America/Montreal, just saying “a few minutes after midnight” has no meaning.

ZoneId

and i can get the time zone object separately in which the above string represents the date.

A time zone is represented by the ZoneId class.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" );

ZonedDateTime

Apply the ZoneId to get a ZonedDateTime which is indeed a point on the timeline, a specific moment in history.

ZonedDateTime zdt = ldt.atZone( z );

zdt.toString(): 2017-01-23T12:34-05:00[America/Montreal]

Instant

I want to convert this to the below format. yyyy-MM-dd HH:mm:ss Z

First, know that a Z literal character is short for Zulu and means UTC. In other words, an offset-from-UTC of zero hours, +00:00.

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

You can extract a Instant object from a ZonedDateTime.

Instant instant = zdt.toInstant();  // Extracting the same moment but in UTC.

To generate a string in standard ISO 8601 format, such as 2017-01-22T18:21:13.354Z, call toString. The standard format has no spaces, uses a T to separate the year-month-date from the hour-minute-second, and appends the Z canonically for an offset of zero.

String output = instant.toString();

instant.toString(): 2017-01-23T17:34:00Z

I strongly suggest using the standard formats whenever possible. If you insist on using spaces as in your stated desired format, either define your own formatting pattern in a DateTimeFormatter object or just do a string manipulation on the output of Instant::toString.

String output = instant.toString()
                       .replace( "T" , " " )  // Substitute SPACE for T.
                       .replace( "Z" , " Z" ); // Insert SPACE before Z.

output: 2017-01-23 17:34:00 Z

Try this code live at IdeOne.com.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

梓梦 2024-10-10 06:50:22

使用 SimpleDateFormat

String string1 = "2009-10-10 12:12:12 ";
SimpleDateFormat sdf =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z")
sdf.setTimeZone(tz);
Date date = sdf.parse(string1);

Use SimpleDateFormat

String string1 = "2009-10-10 12:12:12 ";
SimpleDateFormat sdf =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z")
sdf.setTimeZone(tz);
Date date = sdf.parse(string1);
半衾梦 2024-10-10 06:50:22

毫无疑问,通常使用的格式将是 2014-10-05T15:23:01Z (TZ) 的形式,

因此必须使用此代码,

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
String dateInString = "2014-10-05T15:23:01Z";

 try {

     Date date = formatter.parse(dateInString.replaceAll("Z$", "+0000"));
     System.out.println(date);

 } catch (ParseException e) {
     e.printStackTrace();
 }

其输出将为 Sun Oct 05 20:53 :01 IST 2014

但是,我不确定为什么我们必须替换All“Z”,如果不添加replaceAll,程序将会失败。

Undoubtedly, the format which is generally used will be of a form 2014-10-05T15:23:01Z (TZ)

For that one has to use this code

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
String dateInString = "2014-10-05T15:23:01Z";

 try {

     Date date = formatter.parse(dateInString.replaceAll("Z$", "+0000"));
     System.out.println(date);

 } catch (ParseException e) {
     e.printStackTrace();
 }

Its output will be Sun Oct 05 20:53:01 IST 2014

However, I am not sure why we had to replaceAll "Z" if you do not add replaceAll the program will fail.

恏ㄋ傷疤忘ㄋ疼 2024-10-10 06:50:22

使用您的日期创建 SimpleDateFormat 的新实例图案。之后,您可以调用它的 parse 方法将日期字符串转换为 java.util.Date 对象。

Create a new instance of SimpleDateFormat using your date pattern. Afterwards you can call it's parse method to convert date strings to a java.util.Date object.

静若繁花 2024-10-10 06:50:22

请尝试使用“yyyy-MM-dd HH:mm:ss Z”格式,
例如:“2020-12-11 22:59:59 GMT”,您可以使用不同的时区,如 PST、GMT 等。

Please try this for the format "yyyy-MM-dd HH:mm:ss Z",
Eg: "2020-12-11 22:59:59 GMT", you can use different time zones like PST, GMT, etc.

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