如何使用Joda日期时间将字符串日期转换为UTC格式。

huangapple go评论65阅读模式
英文:

how to convert string date in UTC format using joda date time

问题

public static String convertInDateTimeSecondTOJodaTime(String dateTime) {
    try {
        DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
        DateTime date = formatter.parseDateTime(dateTime).withZoneRetainFields(DateTimeZone.UTC);
        return date.toString("h:mm aa");
    } catch (Exception e) {
        return null;
    }
}

main(){
    print(convertInDateTimeSecondTOJodaTime("2020-04-09T07:31:16Z"))
}

我试图使用 Joda 时间库将给定的 UTC 格式日期时间转换为伦敦时间。但结果显示的时间比预期提前了一个小时。请帮我看看我做错了什么。

预期结果是伦敦时间,所以在这个例子中应该是上午 8:31。

英文:
 public static String convertInDateTimeSecondTOJodaTime(String dateTime) {
        try {
            DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
            DateTime date = formatter.parseDateTime(dateTime).withZoneRetainFields(DateTimeZone.UTC);
            return date.toString("h:mm aa");
        } catch (Exception e) {
            return null;
        }
    }

main(){
print(convertInDateTimeSecondTOJodaTime("2020-04-09T07:31:16Z"))
}

I am trying to convert given date-time in UTC format using joda date time it's giving wrong time it's given one hour before please help me what I am doing wrong.

The desired result is in London time, so 8:31 AM in this case.

答案1

得分: 1

import java.util.Date;
import java.util.TimeZone;
import java.text.SimpleDateFormat;

public class CurrentUtcDate {
    public static void main(String[] args) {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        System.out.println("UTC Time is: " + dateFormat.format(date));
    }
}

输出结果:

UTC Time is: 22-01-2018 13:14:35

你可以在这里查看:https://www.quora.com/How-do-I-get-the-current-UTC-date-using-Java

英文:
import java.util.Date;
import java.util.TimeZone;
import java.text.SimpleDateFormat;
 
public class CurrentUtcDate {
	public static void main(String[] args) {
		Date date = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
		dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
		System.out.println("UTC Time is: " + dateFormat.format(date));
	}
}
 
Output
UTC Time is: 22-01-2018 13:14:35

You can check here https://www.quora.com/How-do-I-get-the-current-UTC-date-using-Java

答案2

得分: 0

以下是翻译好的部分:

如您需要使用Joda DateTime,您需要使用Joda的格式化程序。
您正在返回具有模式“h:mm aa”的日期,因此我假设您需要从日期中提取时间。

以下代码应该有效:

```java
import java.util.Locale;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class MyDateCoonverter {

    public static void main(String a[]) {

        System.out.println(convertInDateTimeSecondTOJodaTime("2020-04-09T07:31:16Z"));
    }

    public static String convertInDateTimeSecondTOJodaTime(String dateTime) {
        DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
        DateTime dt = formatter.parseDateTime(dateTime);
        return dt.toString("h:mm aa", Locale.ENGLISH);
    }
}

它的输出为:
7:31 AM

如果您不想使用任何第三方库,但仍想从日期中提取时间,您可以使用Java的LocalTime。


<details>
<summary>英文:</summary>

As you need to you use Joda DateTime, you need to use formatter of Joda.
You are returning date with pattern &quot;h:mm aa&quot; so I assume you need to extract time from the date. 

Below code should work:

import java.util.Locale;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class MyDateCoonverter {

public static void main(String a[]) {

	System.out.println(convertInDateTimeSecondTOJodaTime(&quot;2020-04-09T07:31:16Z&quot;));
}

public static String convertInDateTimeSecondTOJodaTime(String dateTime) {
		DateTimeFormatter formatter = DateTimeFormat.forPattern(&quot;yyyy-MM-dd&#39;T&#39;HH:mm:ss&#39;Z&#39;&quot;);
		DateTime dt = formatter.parseDateTime(dateTime);
		return dt.toString(&quot;h:mm aa&quot;, Locale.ENGLISH);
}

}


It gives output as:
7:31 AM

If you don&#39;t want to use any third party library &amp; still want to extract only time from date, you can use Java&#39;s LocalTime.

</details>



# 答案3
**得分**: 0

如果您正在使用Java 8或更新版本,应避免使用java.util.Date(已弃用)或Joda Time(已被Java 8的新DATE API替代,使用java.time包):

```java
public static void main(String[] args) {
    String date = "2020-04-09T07:31:16Z";
    String formatedDate = ZonedDateTime.parse(date).format(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT));
    System.out.println(formatedDate); //输出:"7:31 AM"
}
英文:

If you are using Java 8 or newer, you should not use java.util.Date (deprecated) or Joda Time (replaced by the new DATE API of Java 8 with java.time package) :

public static void main(String[] args) {
        String date = &quot;2020-04-09T07:31:16Z&quot;;
        String formatedDate = ZonedDateTime.parse(date).format(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT));
        System.out.println(formatedDate); //print &quot;7:31 AM&quot;
    }
}

答案4

得分: 0

首先,在您的程序中不要将日期和时间处理为字符串。应当将其处理为适当的日期时间对象。因此,除非是最简单的一次性程序,您不应该希望有一种方法将一个在UTC时间的字符串转换为伦敦时间的另一种格式的字符串。

因此,当您接收字符串输入时,应将其解析为 DateTime 对象:

String stringInput = "2020-04-09T07:31:16Z";
DateTime dt = DateTime.parse(stringInput);
System.out.println("Date-time is: " + dt);

到目前为止的输出是:

Date-time is: 2020-04-09T07:31:16.000Z

我正在利用字符串采用 ISO 8601 格式的事实,这是 Joda-Time 的默认格式,因此我们无需为其显式指定解析格式。

直到您需要生成字符串输出时,将日期和时间转换为所需的时区,并按所需的格式转换为所需的字符串:

DateTimeZone zone = DateTimeZone.forID("Europe/London");
DateTime outputDateTime = dt.withZone(zone);
String output = outputDateTime.toString("h:mm aa");
System.out.println("Output is: " + output);

Output is: 8:31 AM

在您的代码中出了什么问题

  1. 在您的格式模式字符串中,用单引号将 Z 括起来是错误的。您输入字符串中的 Z 表示与UTC的偏移量为0,需要将其解析为偏移量,否则会得到不正确的结果。永远不要在 Z 周围加上那些引号。
  2. 对于在不同时区之间转换,withZoneRetainFields() 是错误的方法。这个方法的意思是保持日期和小时不变,只改变时区,这通常会导致不同的时间点。

发生的情况是,您的字符串被解析为 2020-04-09T07:31:16.000+01:00,这与 UTC 时间的 06:31:16 相同,因此是错误的。然后您将时区替换为 UTC,保持了时间为 07:31:16。然后将此时间格式化并打印出来。

请考虑使用 java.time

正如 Fabien 所说,Joda-Time 已经被 java.time 替代,它是现代的 Java 日期和时间 API。Joda-Time 的主页上写道:

请注意,Joda-Time 被认为是一个基本“完成”的项目。
不计划进行重大增强。如果使用 Java SE 8,请迁移到 java.time(JSR-310)。

链接

英文:

First, don’t handle date and time as strings in your program. Handle them as proper date-time objects. So but for all but the simplest throw-away programs you should not want a method that converts from a string in UTC to a string in London time in a different format.

So when you accept string input, parse into a DateTime object:

	String stringInput = &quot;2020-04-09T07:31:16Z&quot;;
	DateTime dt = DateTime.parse(stringInput);
	System.out.println(&quot;Date-time is: &quot; + dt);

Output so far is:

> Date-time is: 2020-04-09T07:31:16.000Z

I am exploiting the fact that your string is in ISO 8601 format, the default for Joda-Time, so we need no explicit formatter for parsing it.

Not until you need to give string output, convert your date and time to the desired zone and format into the desired string:

	DateTimeZone zone = DateTimeZone.forID(&quot;Europe/London&quot;);
	DateTime outputDateTime = dt.withZone(zone);
	String output = outputDateTime.toString(&quot;h:mm aa&quot;);
	System.out.println(&quot;Output is: &quot; + output);

> Output is: 8:31 AM

What went wrong in your code

  1. Z in single quotes in your format pattern string is wrong. Z in your input string is an offset of 0 from UTC and needs to be parsed as an offset, or you are getting an incorrect result. Never put those quotes around Z.
  2. withZoneRetainFields() is the wrong method to use for converting between time zones. The method name means that the date and hour of day are kept the same and only the time zone changed, which typically leads to a different point in time.

What happened was that your string was parsed into 2020-04-09T07:31:16.000+01:00, which is the same point in time as 06:31:16 UTC, so wrong. You next substituted the time zone to UTC keeping the time of day of 07:31:16. This time was then formatted and printed.

Do consider java.time

As Fabien said, Joda-Time has later been replaced with java.time, the modern Java date and time API. The Joda-Time home page says:

> Note that Joda-Time is considered to be a largely “finished” project.
> No major enhancements are planned. If using Java SE 8, please migrate
> to java.time (JSR-310).

huangapple
  • 本文由 发表于 2020年4月9日 15:50:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/61116324.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定