[英]How to convert string of type YY/MM/DD to java.util.Date?
I have searched but did not find the exact format(YY/MM/DD) for parsing the String.我已经搜索过,但没有找到解析字符串的确切格式(YY/MM/DD)。
How can I convert a string of type YY/MM/DD to java.util.Date
.如何将 YY/MM/DD 类型的字符串转换为
java.util.Date
。 I have strings in the format "160310", "160211".我有格式为“160310”、“160211”的字符串。
You can use SimpleDateFormat
for this.您可以为此使用
SimpleDateFormat
。
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有关更多选项和信息,您可以随时在此处查看有关它的完整文档: http : //docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html
Nit: The format isn't "YY/MM/DD", it's "YYMMDD" (note the slashes). Nit:格式不是“YY/MM/DD”,而是“YYMMDD”(注意斜线)。 Regardless, you can use a
SimpleDateFormat
to parse such strings:无论如何,您可以使用
SimpleDateFormat
来解析此类字符串:
DateFormat df = new SimpleDateFormat("yyMMdd");
Date date = df.parse("160211");
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);`
If you have reached the area of Java 8, you might also consider如果你已经到了 Java 8 的领域,你也可以考虑
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.但实际上,如果可以避免的话,您不会转换为旧的丑陋日期,而是使用您在途中创建的 LocalDate。
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.