我有一个字符串,其中包含以"2014-11-12 16:19:00"
格式从webservice检索的日期时间
我只需要提取12小时格式AM或PM的时间。
我试过但没有得到理想的结果。
public Date validateBreakingNewsDateDate() throws Exception{
Date date = null;
String dtStart = "2014-11-12 16:19:00";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
date= format.parse(dtStart);
Log.e("date", "kardate "+date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return date;
}
答案 0 :(得分:2)
尝试以下代码段
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
答案 1 :(得分:0)
将您的日期传递给此功能,它将返回时间
public String setTime(String date) {
final String OLD_FORMAT = "yyyy-MM-dd HH:mm:ss";
final String NEW_FORMAT = "h:mm a";
String newDate = "";
try {
SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT);
Date d = sdf.parse(date);
sdf.applyPattern(NEW_FORMAT);
newDate = sdf.format(d);
} catch (ParseException e) {
// TODO: handle exception
}
return newDate;
}
例如
public String setTime(String date) {
final String OLD_FORMAT = "yyyy-MM-dd HH:mm:ss";
final String NEW_FORMAT = "h:mm a";
String newDate = "";
try {
sdf = new SimpleDateFormat(OLD_FORMAT);
Date d = sdf.parse("2014-11-12 16:19:00");
sdf.applyPattern(NEW_FORMAT);
newDate = sdf.format(d);
} catch (ParseException e) {
// TODO: handle exception
}
return newDate;
}
输出= 4:19 PM
答案 2 :(得分:0)
试试这个......
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse(dtStart);
String newstring = new SimpleDateFormat("hh:mm aa").format(date);
答案 3 :(得分:0)
您可以使用SimpleDateFormat
获取12小时的时间,如下所示
Date date = null;
String dtStart = "2014-11-12 16:19:00";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd KK:mm:ss");
try {
date = format.parse(dtStart);
Log.e("date", "kardate " + date);
// here hh means hours in 12 hr format and a stands for AM/PM
format = new SimpleDateFormat("hh:mm:ss a");
String desiredTime= format.format(date);
// You will get newDate 04:19:00 pm
Log.e("date", "newDate " + desiredTime);
} catch (Exception e) {
e.printStackTrace();
}
希望它有助于ツ