我在android.On中做了dateTimePicker应用程序,我需要在特定dateTime.Ex之前和之后获得10分钟。如果用户选择“12/12/2010 5:00”,我需要将“12/12/2010 4:50”作为一个值& “12/12/2010 5:10”作为一个值。我怎么做+ 10分钟&特定时间-10分钟?
我的代码:
String DATETIMEBEFORE ;
String DATETIMEAFTER;
...
private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int selectedHour,
int selectedMinute) {
hour = selectedHour;
minute = selectedMinute;
String DATETIME = new StringBuilder()
// Month is 0 based, just add 1
.append(month + 1).append("-").append(day).append("-")
.append(year).append(" ").append(pad(hour)).append(":")
.append(pad(minute)).toString();
如果DATETIME的值=“12/12/2010 5:00”。我需要得到 DATETIMEBEFORE value =“12/12/2010 4:50”& DATETIMEAFTER值=“12/12/2010 5:10”。 感谢。
答案 0 :(得分:1)
OPs代码后更新
public static String getTimeBefore10minutes(String currentDate) {
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm");
try {
// Get calendar set to current date and time with Singapore time zone
Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("Asia/Calcutta"));
calendar.setTime(format.parse(currentDate));
//Set calendar before 10 minutes
calendar.add(Calendar.MINUTE, -10);
//Formatter
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm");
formatter.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
return formatter.format(calendar.getTime());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static String getTimeAfter10minutes(String currentDate) {
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm");
try {
// Get calendar set to current date and time with Singapore time zone
Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("Asia/Calcutta"));
calendar.setTime(format.parse(currentDate));
//Set calendar before 10 minutes
calendar.add(Calendar.MINUTE, 10);
//Formatter
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm");
formatter.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
return formatter.format(calendar.getTime());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
并打电话给
getTimeAfter10minutes("12/12/2010 5:00");
getTimeBefore10minutes("12/12/2010 5:00");
结果将是
12/12/2010 05:10
12/12/2010 04:50
详细了解我的博客Calculate Date Ranges
答案 1 :(得分:0)
如果您有以毫秒为单位的选定时间,
long now = System.currentTimeMillis(); // or any time value in miliseconds
long tenMinuteBefore = now - 600000;
long tenMinuteAfter = now + 600000;