简体   繁体   中英

How change String to Date format

I have this string: 2018-09-22 10:17:24.772000 I want to convert it to 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

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 :

    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)

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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