我想知道使用AM / PM多少小时,但我只能在不使用AM / PM的情况下获得小时数
这是我的代码
private TextView textView,textView1,txtdiff;
String dateStart = "03/13/17 08:30:00";
String dateStop = "03/13/17 05:30:00";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.current_date_view);
textView1 = (TextView) findViewById(R.id.secondDate);
txtdiff = (TextView) findViewById(R.id.difference);
textView.setText("First Date: "+ dateStart);
textView1.setText("Second Date: "+ dateStop);
}
public void getCurrentDate(View view) {
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
String seconds = Long.toString(diffSeconds);
String minutes = Long.toString(diffMinutes);
String hours = Long.toString(diffHours);
String days = Long.toString(diffDays);
txtdiff.setText(hours + " Hours");
} catch (Exception e) {
e.printStackTrace();
}
}
问题是我想添加AM PM。
我尝试使用AM和PM添加字符串
String dateStart = "03/13/17 08:30:00 am";
String dateStop = "03/13/17 05:30:00 pm";
并使用SimpleDate格式:
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss a");
但不幸的是它不起作用,任何人都可以指出我正确的方向
答案 0 :(得分:1)
你应该使用小' hh'当您定义小时格式时
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
否则,您的值ara被视为使用24h格式定义,08和05将在早上,即使您已指定上午/下午