How to convert string of type YY/MM/DD to java.util.Date?

╄→尐↘猪︶ㄣ 提交于 2019-12-25 18:12:09

问题


I have searched but did not find the exact format(YY/MM/DD) for parsing the String.

How can I convert a string of type YY/MM/DD to java.util.Date. I have strings in the format "160310", "160211".


回答1:


You can use SimpleDateFormat for this.

String target = "160211";
DateFormat df = new SimpleDateFormat("yyMMdd", Locale.ENGLISH);
Date result =  df.parse(target);

For more options and info you can always checkout the full documentation about it here: http://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html




回答2:


Nit: The format isn't "YY/MM/DD", it's "YYMMDD" (note the slashes). Regardless, you can use a SimpleDateFormat to parse such strings:

DateFormat df = new SimpleDateFormat("yyMMdd");
Date date = df.parse("160211");



回答3:


If you have reached the area of Java 8, you might also consider

        Date dt = Date.valueOf(LocalDate.from(DateTimeFormatter.ofPattern("yyMMdd").parse("160123")));

But in fact, you would not do the conversion to the old ugly date if you can avoid it, but rather go along with the LocalDate you created on your way.




回答4:


Use the following code , It will

    String mydate="160310";
    SimpleDateFormat sd=new SimpleDateFormat("YYmmdd",Locale.ENGLISH);
    Date date = sd.parse(mydate);
    System.out.println(date);`



回答5:


Like this:

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

public class DateTester {

    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");

        Date date = null;
        try {
            date = sdf.parse("160310");
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(date);
    }
}


来源:https://stackoverflow.com/questions/36172920/how-to-convert-string-of-type-yy-mm-dd-to-java-util-date

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!