我有一个包含六个数字的字符串:650310
。它以1965 march 10
格式表示YYMMDD
。
是否有任何方法可以将此格式识别为10 march 1965
?
目前这是我的做法,效果不是很好。
public class Example {
public static void main(String args[]) {
//date in YYMMDD
//String x = "650310";
String x = "161020";
System.out.print(x.substring(4, 6)+" ");
if (Integer.parseInt(x.substring(2, 4)) == 10) {
System.out.print("October"+" ");
}
else if (Integer.parseInt(x.substring(2, 4)) == 03) {
System.out.print("March"+" ");
}
if (Integer.parseInt(x.substring(0, 2)) > 50) {
String yr = "19" + x.substring(0, 2);
System.out.println(yr);
} else if (Integer.parseInt(x.substring(0, 2)) < 50) {
String yr = "20" + x.substring(0, 2);
System.out.println(yr);
}
}
}
output : 20 October 2016
答案 0 :(得分:3)
使用Java的SimpleDateFormat:
SimpleDateFormat inFormat = new SimpleDateFormat( "yyMMdd" );
Date theDate = format.parse( "650310" );
现在您有一个Date对象,您可以使用它来以其他格式显示日期:
SimpleDateFormat outFormat = new SimpleDateFormat( "dd MMMMM yyyy" );
StringBuffer output = outFormat.format( theDate );
使用output.toString()
显示新格式化的日期。祝好运。
答案 1 :(得分:1)
试试这个例子
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Example {
public static void main(String args[]) throws ParseException {
SimpleDateFormat s = new SimpleDateFormat( "yyMMdd" );
Date theDate = s.parse( "650310" );
SimpleDateFormat p = new SimpleDateFormat( "dd MMMMM yyyy" );
System.out.println(p.format(theDate));
}
}
输出 1965年3月10日
答案 2 :(得分:0)
使用SimpleDateFormat进行日期解析。例如:
SimpleDateFormat format = new SimpleDateFormat("yyMMdd");
try {
System.out.println(format.parse("900310"));
} catch (ParseException e) {
e.printStackTrace();
}
输出:3月10日星期六00:00:00 MSK 1990
编辑:如果要解析日期,请尝试使用DateFormat获取Date
!!!!然后你可以用自己的方式格式化它。我不同意你的downvote。
SimpleDateFormat format = new SimpleDateFormat("yyMMdd");
try {
Date parse = format.parse("900310");
format.applyPattern("dd MMMM yyyy");
System.out.println(format.format(parse));
} catch (ParseException e) {
e.printStackTrace();
}
输出10 /Март/ 1990
答案 3 :(得分:0)
这link会有所帮助。创建一个SimpleDateFormat对象并使用它将字符串解析为Date并将Dates格式化为字符串。