Java日期格式:YYYYMMDDHHMMss.000Z,表示格林尼治标准时间(GMT)。

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

Java date with the format : YYYYMMDDHHMMss.000Z as GMT

问题

我需要在我的时区获取今天午夜的日期,格式为YYYYMMDDHHMMss.000Z,作为GMT中的日期和时间。
我对日期感兴趣,不关心一天中的具体时间。
在我的系统中,当我得到一个日期:20201001220000.000Z,对于GMT来说,这是一个属于夏令时的日期20201003。我之所以提出这个问题,是因为我需要将20201001220000.000Z与今天的日期进行比较。

我需要以yyyyMMddHHmmss.SSSZ的格式获取日期(今天的午夜)。在我的系统中,今天的午夜日期20201004是:20201003220000.000Z,这个日期将与其他日期进行比较,例如20201002220000.000Z。问题是我无法获取午夜时间。

英文:

I need to get today’s date at midnight in my time zone in the format YYYYMMDDHHMMss.000Z as date and time in GMT.
I'm interested in the date, not the time of day.
In my system when I have got a date: 20201001220000.000Z it is a day 20201003 as summertime for GMT. I am asking this question because I need to compare the 20201001220000.000Z with today’s date.

I need to get the date ( TODAY midnight) in format yyyyMMddHHmmss.SSSZ. TODAY midnight 20201004 in my system is: 20201003220000.000Z this date will be compared with other dates e.g 20201002220000.000Z. The problem is that I can't get midnight.

答案1

得分: 3

## java.time

**Edit:**

我倾向于理解您希望将今天的日期按您的格式转换为UTCGMT中的其他日期时间字符串并以相同的格式进行比较为了比较日期和时间我建议您比较日期时间对象而不是字符串因此有两个选项

1. 解析现有字符串将其转换为您所在时区的日期然后将其与今天的日期进行比较
2. 将现有字符串解析为某个时间点然后与今天日期的开始进行比较

让我们在代码中看到这两个选项

**1. 转换为日期并比较日期**

```java
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuuMMddHHmmss.SSSX");
ZoneId zone = ZoneId.systemDefault();

LocalDate today = LocalDate.now(zone);

String gmtString = "20201001220000.000Z";
LocalDate dateFromGmtString = formatter.parse(gmtString, Instant::from)
        .atZone(zone)
        .toLocalDate();

if (dateFromGmtString.isAfter(today)) {
    System.out.println(gmtString + " 在未来");
} else if (dateFromGmtString.isBefore(today)) {
    System.out.println(gmtString + " 在过去");
} else {
    System.out.println(gmtString + " 是今天");
}

输出:

20201001220000.000Z 在过去

2. 找到今天日期的开始并比较时间:

Instant startOfDay = LocalDate.now(zone).atStartOfDay(zone).toInstant();

String gmtString = "20201001220000.000Z";
Instant timeFromGmtString = formatter.parse(gmtString, Instant::from);

if (timeFromGmtString.isBefore(startOfDay)) {
    System.out.println(gmtString + " 在过去");
} else {
    System.out.println(gmtString + " 是今天或以后");
}

输出:

20201001220000.000Z 在过去

原始答案

您可能在寻找以下内容。我建议您在处理日期和时间时使用现代的 Java 日期和时间 API java.time

DateTimeFormatter sourceFormatter = DateTimeFormatter.ofPattern("uuuuMMddHHmmss.SSSX");

String gmtString = "20201001220000.000Z";

Instant instant = sourceFormatter.parse(gmtString, Instant::from);
LocalDate date = instant.atZone(ZoneId.systemDefault()).toLocalDate();
String dayString = date.format(DateTimeFormatter.BASIC_ISO_DATE);

System.out.println(dayString);

当我在Europe/Warsaw时区运行代码时,输出为:

20201002

因此,日期已从GMT的10月1日转换为波兰的10月2日。

编辑:

… 如何获取午夜?

要获取一天的开始(通常为00:00):

ZonedDateTime startOfDay = time.atZone(ZoneId.systemDefault())
        .truncatedTo(ChronoUnit.DAYS);
System.out.println(startOfDay);

输出:

2020-10-02T00:00+02:00[Europe/Warsaw]

链接: Oracle教程:日期时间,解释了如何使用java.time


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

## java.time

**Edit:**

I tend to understand that you want to format today’s date into your format for comparison with other date-time strings in UTC (GMT) in the same format. For comparing dates and times I suggest that you compare date-time objects, not strings. So the options are two:

 1. Parse the existing string, convert it to a date in your time zone and compare it to today’s date.
 2. Parse your existing string into a point in time. Compare to the start of today’s date.

Let’s see both options in code.

**1. Convert to date and compare dates:**

		DateTimeFormatter formatter = DateTimeFormatter.ofPattern(&quot;uuuuMMddHHmmss.SSSX&quot;);
		ZoneId zone = ZoneId.systemDefault();
		
		LocalDate today = LocalDate.now(zone);
		
		String gmtString = &quot;20201001220000.000Z&quot;;
		LocalDate dateFromGmtString = formatter.parse(gmtString, Instant::from)
				.atZone(zone)
				.toLocalDate();
		
		if (dateFromGmtString.isAfter(today)) {
			System.out.println(gmtString + &quot; is in the future&quot;);
		} else if (dateFromGmtString.isBefore(today)) {
			System.out.println(gmtString + &quot; was on a past date&quot;);
		} else {
			System.out.println(gmtString + &quot; is today&quot;);
		}

Output:

&gt; 20201001220000.000Z was on a past date

**2. Find start of today’s date and compare times**

		Instant startOfDay = LocalDate.now(zone).atStartOfDay(zone).toInstant();
		
		String gmtString = &quot;20201001220000.000Z&quot;;
		Instant timeFromGmtString = formatter.parse(gmtString, Instant::from);
		
		if (timeFromGmtString.isBefore(startOfDay)) {
			System.out.println(gmtString + &quot; was on a past date&quot;);
		} else {
			System.out.println(gmtString + &quot; is today or later&quot;);
		}

&gt; 20201001220000.000Z was on a past date

**Original answer**

You may be after the following. I recommend that you use `java.time`, the modern Java date and time API, for your date and time work.

    DateTimeFormatter sourceFormatter = DateTimeFormatter.ofPattern(&quot;uuuuMMddHHmmss.SSSX&quot;);
    
    String gmtString = &quot;20201001220000.000Z&quot;;
    
    Instant instant = sourceFormatter.parse(gmtString, Instant::from);
    LocalDate date = instant.atZone(ZoneId.systemDefault()).toLocalDate();
    String dayString = date.format(DateTimeFormatter.BASIC_ISO_DATE);
    
    System.out.println(dayString);

When I run the code in Europe/Warsaw time zone, the output is:

&gt; 20201002

So the date has been converted from October 1 GMT to October 2 in Poland.

Edit:

&gt; … How can I get midnight?

To get the start of the day (usually 00:00):

		ZonedDateTime startOfDay = time.atZone(ZoneId.systemDefault())
				.truncatedTo(ChronoUnit.DAYS);
		System.out.println(startOfDay);

&gt; 2020-10-02T00:00+02:00[Europe/Warsaw]

**Link:** [Oracle tutorial: Date Time](https://docs.oracle.com/javase/tutorial/datetime/) explaining how to use java.time.




</details>



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

尝试这个。

```java
String format = "yyyy-MM-dd HH:mm:ss.SSS O";
		
ZonedDateTime zdt = ZonedDateTime.now().withZoneSameInstant(ZoneId.of("GMT"));
System.out.println(zdt.format(DateTimeFormatter.ofPattern(format)));

以美国东海岸时间打印为

2020-10-03 14:47:18.809 GMT

您可以根据需要删除空格、短横线和冒号。但请不要使用过时的Date或相关的格式化程序。请使用java.time包中的类。

英文:

Try this.

String format = &quot;yyyy-MM-dd HH:mm:ss.SSS O&quot;;
		
ZonedDateTime zdt = ZonedDateTime.now().withZoneSameInstant(ZoneId.of(&quot;GMT&quot;));
System.out.println(zdt.format(DateTimeFormatter.ofPattern(format)));

Prints a US East coast time as

2020-10-03 14:47:18.809 GMT

You can delete the spaces, dashes and colons as desired. But do not use Date or related formatters as they are outdated. Use the classes from the java.time package.

答案3

得分: 0

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        // 今天
        LocalDate today = LocalDate.now();

        // JVM 默认时区的午夜
        ZonedDateTime zdt = today.atStartOfDay(ZoneId.systemDefault());

        // 以默认格式打印 zdt,即 zdt.toString() 返回的值
        System.out.println(zdt);

        // 以自定义格式打印 zdt
        DateTimeFormatter customFormat = DateTimeFormatter.ofPattern("yyyyMMddHHmmss.SSSZ");
        String dateTimeStrCustom = zdt.format(customFormat);
        System.out.println(dateTimeStrCustom);
    }
}

输出:

2020-10-04T00:00+01:00[Europe/London]
20201004000000.000+0100

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

You can do it as follows:

    import java.time.LocalDate;
    import java.time.ZoneId;
    import java.time.ZonedDateTime;
    import java.time.format.DateTimeFormatter;
    
    public class Main {
    	public static void main(String[] args) {
    		// Today
    		LocalDate today = LocalDate.now();
    
    		// Midnight in the JVM&#39;s default time-zone
    		ZonedDateTime zdt = today.atStartOfDay(ZoneId.systemDefault());
    
    		// Printing zdt in its default format i.e. value returned by zdt.toString()
    		System.out.println(zdt);
    
    		// Printing zdt in your custom format
    		DateTimeFormatter customFormat = DateTimeFormatter.ofPattern(&quot;yyyyMMddHHmmss.SSSZ&quot;);
    		String dateTimeStrCustom = zdt.format(customFormat);
    		System.out.println(dateTimeStrCustom);
    	}
    }

**Output:**

    2020-10-04T00:00+01:00[Europe/London]
    20201004000000.000+0100



</details>



huangapple
  • 本文由 发表于 2020年10月3日 22:21:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/64185231.html
匿名

发表评论

匿名网友

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

确定