简体   繁体   English

如何将字符串更改为日期格式

[英]How change String to Date format

I have this string: 2018-09-22 10:17:24.772000 I want to convert it to Date: 我有这个字符串:2018-09-22 10:17:24.772000我想将其转换为Date:

 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");

    String sdate = "2018-09-22 10:17:24.772000";
    Date dateFrom = simpleDateFormat.parse(sdate);

but it shows: Sat Sep 22 10:17:24 GMT+03:30 2018 但它显示:2018年9月22日星期六10:17:24 GMT + 03:30

Here is what you should do instead, you are printing date object itself, you should print its format. 这是您应该做的,您正在打印日期对象本身,应该打印其格式。

I will provide the code with old date api and new local date api : 我将为代码提供旧的日期api和新的本地日期api:

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");

    String sdate = "2018-09-22 10:17:24.772000";
    Date dateFrom = simpleDateFormat.parse(sdate);

    System.out.println(dateFrom); // this is what you do
    System.out.println(simpleDateFormat.format(dateFrom)); // this is what you should do

    // below is from new java.time package

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS");
    System.out.println(LocalDateTime.parse(sdate, formatter).format(formatter));

output is : 输出是:

Sat Sep 22 10:30:16 EET 2018
2018-09-22 10:30:16.000000

2018-09-22 10:17:24.772000

Looks to me like you have converted it to a Date. 在我看来,您已将其转换为日期。 What is your desired result? 您想要的结果是什么? I suspect what you are wanting to do is to create another Simple date format that shows your expected format and then use simpledateformat2.format(dateFrom) 我怀疑您要执行的操作是创建另一个显示您期望格式的简单日期格式,然后使用simpledateformat2.format(dateFrom)

I should also point out based on past experience that you should add a Locale to your simple date formats otherwise a device with a different language setting may not be able to execute this code 我还应根据过去的经验指出,您应该将区域设置添加到简单的日期格式中,否则具有不同语言设置的设备可能无法执行此代码

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS", Locale.US);

Hope This will help you 希望这个能对您有所帮助

public class Utils {

    public static void main(String[] args) {

        String mytime="2018-09-22 10:17:24.772000";
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss.SSSSSS");

        Date myDate = null;
        try {
            myDate = dateFormat.parse(mytime);

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

        SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd");
        String finalDate = timeFormat.format(myDate);

        System.out.println(finalDate);
    }
}

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

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