Java 安卓-字符串到时间?

Java 安卓-字符串到时间?,java,android,Java,Android,我有一个字符串..>>字符串x=06:30 如何将此字符串值更改为时间 如何将其与当前时间进行比较,看哪个更小?如果您知道时间总是以该格式显示,则无需转换为时间。相反,用相同的格式格式化当前时间,并简单地比较字符串 既然您标记了android,我假设您没有Java 8: String now = new SimpleDateFormat("HH:mm").format(new Date()); if (x.compareTo(now) < 0) { // x is before n

我有一个字符串..>>字符串x=06:30

如何将此字符串值更改为时间


如何将其与当前时间进行比较,看哪个更小?

如果您知道时间总是以该格式显示,则无需转换为时间。相反,用相同的格式格式化当前时间,并简单地比较字符串

既然您标记了android,我假设您没有Java 8:

String now = new SimpleDateFormat("HH:mm").format(new Date());
if (x.compareTo(now) < 0) {
    // x is before now
}

使用Joda时间库:

DateTimeFormatter fmt = DateTimeFormat.forPattern("HH:mm");
LocalTime time = fmt.parseLocalTime(x);
LocalTime now = new LocalTime();
if (now.before(time)) { /* now is before time */ }

但要注意时区数据和两个时间戳的设置。上面的示例假设本地时间具有默认时区设置。

约翰·汤姆森的代码要好得多,请忽略这一点

首先,我假设你的刺的形式是小时:分钟

import java.util.Calendar

Calendar c = Calendar.getInstance(); 
int currentHour = c.get(Calendar.HOUR);
int currentMinute = c.get(Calendar.Minute);
String s = "06:30";
int hour = Integer.parseInt(s.substring(0,2));
int minute = Integer.parseInt(s.substring(3,5));
编写比较这些值的代码应该很容易。您可以通过比较小时和分钟,或者将两者合并为一个totalMinutes,然后进行比较来实现这一点。例如:

int totalMinutes = (60*hour)+minute;
int totalCurrentMinutes = (60*currentHour)+currentMinute;
return totalMinutes > totalCurrentMinutes; //this will return True if the time you are testing for is greater than the current time.

当问题是如何比较时,说比较应该很容易,所以不是完全有帮助。尤其是因为比较小时和分钟这两个值被新的程序员认为是错误的。这是真的,我刚刚修正了这个问题。ThanksFYI,像java.util.date和now这样麻烦的旧日期时间类被这些类取代了。大部分java.time功能都在中向后移植到Java6和Java7。在项目中对Android进行了进一步调整。啊,谢谢,我已经有一段时间没有编写Android应用程序了。很高兴知道如果字符串值始终是12h格式,如何将其更改为24h格式,因为比较12h无法正常工作不能是没有AM/PM后缀的12小时刻度,否则您将如何比较06:30和当前下午3:58的PDT时间?那是早上6:30还是晚上6:30?我现在知道你的回答对我有帮助:仅供参考,项目已经开始,团队建议迁移到课堂上。大部分java.time功能都在中向后移植到Java6和Java7。在项目中进一步适应Android。
int totalMinutes = (60*hour)+minute;
int totalCurrentMinutes = (60*currentHour)+currentMinute;
return totalMinutes > totalCurrentMinutes; //this will return True if the time you are testing for is greater than the current time.