我想将字符串转换为日期格式。我尝试了很多方法,但都没有成功。我的字符串是"Jan 17, 2012"。我想将它转换为"2011-10-17"。请问有人可以告诉我如何做到这一点吗?如果您有任何已解决的示例,那将是真正的帮助!
我想将字符串转换为日期格式。我尝试了很多方法,但都没有成功。我的字符串是"Jan 17, 2012"。我想将它转换为"2011-10-17"。请问有人可以告诉我如何做到这一点吗?如果您有任何已解决的示例,那将是真正的帮助!
try {
String strDate = "Jan 17, 2012";
//current date format
SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy");
Date objDate = dateFormat.parse(strDate);
//Expected date format
SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
String finalDate = dateFormat2.format(objDate);
Log.d("Date Format:", "Final Date:"+finalDate)
} catch (Exception e) {
e.printStackTrace();
}
String format = "yyyy-MM-dd";
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
yyyy-MM-dd 1969-12-31
yyyy-MM-dd 1970-01-01
更多信息请查看这里
。 此处涉及IT技术相关内容。我建议使用Joda Time,它是Java中处理日期/时间最好、最简单的库,而且它是线程安全的(与Java中默认的格式化类相比)。
您可以按照以下方式使用它:
// Define formatters:
DateTimeFormatter inputFormat = DateTimeFormat.forPattern("MMM dd, yyyy");
DateTimeFormatter outputFormat = DateTimeFormat.forPattern("yyyy-MM-dd");
// Do your conversion:
String inputDate = "Jan 17, 2012";
DateTime date = inputFormat.parseDateTime(inputDate);
String outputDate = outputFormat.print(date);
// or:
String outputDate = date.toString(outputFormat);
// or:
String outputDate = date.toString("yyyy-MM-dd");
// Result: 2012-01-17
public static Date getDateFromString(String date) {
Date dt = null;
if (date != null) {
for (String sdf : supportedDateFormats) {
try {
dt = new Date(new SimpleDateFormat(sdf).parse(date).getTime());
break;
} catch (ParseException pe) {
pe.printStackTrace();
}
}
}
return dt;
}
public static String getTime(long milliseconds)
{
return DateFormat.format("MMM dd, yyyy", milliseconds).toString();
}
你也可以尝试使用日期格式类更好地理解。
You can't convert date from one format to other. while you are taking the date take you have take the date which ever format the you want. If you want the date in yyyy-mm-dd. You can get this by using following way.
java.util.Calendar calc = java.util.Calendar.getInstance();
int day = calc.get(java.util.Calendar.DATE);
int month = calc.get(java.util.Calendar.MONTH)+1;
int year = calc.get(java.util.Calendar.YEAR);
String currentdate = year +"/"+month +"/"+day ;
尝试这个简单的方法:
fun getFormattedDate(strDate:String): String {
try {
val dateFormat = SimpleDateFormat("dd/mm/yyyy")//old format
val dateFormat2 = SimpleDateFormat("mm/dd/yyyy")//require new formate
val objDate = dateFormat.parse(strDate)
return dateFormat2.format(objDate)
} catch (e:Exception) {
return ""
}
}