简体   繁体   English

在 Java 中将字符串(带有保留字符)转换为日期

[英]Convert a String (with reserved characters) to Date in Java

I want to convert a String (with reserved characters) to Date in Java我想在 Java 中将String (带有保留字符)转换为Date

I have a string with some reserved characters in it.我有一个带有一些保留字符的字符串。 I am getting it from some source.我从某个来源得到它。 Also I get the format of it from the same source.我也从同一来源获得它的格式。 I tried to convert that string to a date but I was unable to.我试图将该字符串转换为日期,但无法转换。

The date I get:我得到的日期:

{ts '2021-03-24 12:52:38.933'}

The format I get:我得到的格式:

'{ts' ''yyyy-MM-dd HH:mm:ss{.SSS}[Z]'''}'

I tried with the sample code snippet but since {} are reserved characters and also ts is an invalid character for parsing, I am unable to parse it.我尝试使用示例代码片段,但由于{}是保留字符,而且 ts 是用于解析的无效字符,因此我无法解析它。 Please help with how I can solve this.请帮助我如何解决这个问题。

Obviously I can do some string manipulation and convert it to a format I want but I don't want to do that.显然我可以做一些字符串操作并将其转换为我想要的格式,但我不想这样做。

String dateInString = "{ts '2021-03-24 12:52:38.933'}";

SimpleDateFormat sdf = new SimpleDateFormat("{ts' ''yyyy-MM-dd HH:mm:ss{.SSS}[Z]'''}", Locale.ENGLISH);
try {
    Date date = sdf.parse(dateInString);
    System.out.println(date);
} catch (ParseException e) {
    e.printStackTrace();
}

You need to escape ' with another ' .你需要'和另一个'一起逃脱。

Demo:演示:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class Main {
    public static void main(String[] args) throws ParseException {
        String dateInString = "{ts '2021-03-24 12:52:38.933'}";
        SimpleDateFormat parser = new SimpleDateFormat("'{ts '''yyyy-MM-dd HH:mm:ss.SSS'''}'", Locale.ENGLISH);
        Date date = parser.parse(dateInString);
        System.out.println(date);

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
        System.out.println(formatter.format(date));
    }
}

Output:输出:

Wed Mar 24 12:52:38 GMT 2021
2021-03-24T12:52:38.933

ONLINE DEMO在线演示

Note that the java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone.请注意, java.util Date-Time API 及其格式化 API SimpleDateFormat已过时且容易出错。 It is recommended to stop using them completely and switch to the modern Date-Time API * .建议完全停止使用它们并切换到现代 Date-Time API *

Solution using java.time , the modern Date-Time API:使用现代日期时间 API java.time解决方案:

import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) throws ParseException {
        String dateInString = "{ts '2021-03-24 12:52:38.933'}";
        DateTimeFormatter parser = DateTimeFormatter.ofPattern("'{ts '''yyyy-MM-dd HH:mm:ss.SSS'''}'", Locale.ENGLISH);
        LocalDateTime ldt = LocalDateTime.parse(dateInString, parser);
        System.out.println(ldt);
    }
}

Output:输出:

2021-03-24T12:52:38.933

ONLINE DEMO在线演示

Learn more about the modern Date-Time API from Trail: Date Time .Trail: Date Time 中了解有关现代日期时间 API 的更多信息。


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project . * 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用ThreeTen-Backport,它将大部分java.time功能向后移植到 Java 6 和 7。如果您正在为 Android 项目和您的 Android API 工作级别仍然不符合 Java-8,请检查 通过 desugaringHow to use ThreeTenABP in Android Project 可用的 Java 8+ APIs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM