简体   繁体   English

Android-使用简单日期格式将字符串转换为时间(仅)

[英]Android - String to Time(only) using Simple Date Format

So what i'm trying to do is basically, i have a String variable, and i'm trying to convert that string to a time format, so that i can then use that time to create an alert for that day. 因此,我基本上想做的是,我有一个String变量,并且我正在尝试将该字符串转换为时间格式,以便随后可以使用该时间为当天创建警报。

For example. 例如。

String stringTime = "1:05 PM" 字符串stringTime =“ 1:05 PM”

and i want to convert that to a date format so an alarm will be set to go off at the next 1:05PM. 我想将其转换为日期格式,以便将闹钟设置为在下一个1:05 PM发出。

When i try using the SimpleDateFormat, it shows up as a date and time, and the date is back in 1970. See code below. 当我尝试使用SimpleDateFormat时,它显示为日期和时间,日期可追溯到1970年。请参见下面的代码。

Date[] date_formatted_times_A;
SimpleDateFormat formatter = new SimpleDateFormat("h:m a");

public Date[] DateConverterA (String[] times_A){

            date_formatted_times_A = new Date[times_A.length];

            for(int i=0;i<times_A.length;i++)
            {
                try {
                    date_formatted_times_A[i] = formatter.parse(times_A[i]);



                } catch (java.text.ParseException e) {
                    e.printStackTrace();
                }
            }
            return date_formatted_times_A;

}

But the result i get from this, in the case the string time is 1:05 PM is "Thu Jan 01 13:05:00 GMT 1970". 但是我从中得到的结果是,在字符串时间是1:05 PM的情况下,是“ Thu Jan 01 13:05:00 GMT 1970”。 I'm totally lost as to how i should proceed. 我完全迷失了应该如何进行。 Please remember i only want the time, and i need it to be in a way which i can then use to set an alarm with it after. 请记住,我只想要时间,而我需要这样一种方式,之后便可以用来设置闹钟了。 The times will be stored in a DATE array (or what ever array you think is more suitable). 时间将存储在DATE数组(或您认为更合适的数组)中。 24hr or 12hr is fine! 24小时或12小时就可以了!

Your Simple Date Format should be: 您的简单日期格式应为:
SimpleDateFormat formatter = new SimpleDateFormat(hh:mm a");

Try the following and learn different formats yourself: 尝试以下方法并自己学习其他格式:

try {
   SimpleDateFormat format = new SimpleDateFormat("hh:mm a"); //if 24 hour format
   // or
   SimpleDateFormat format = new SimpleDateFormat("HH:mm"); // 12 hour format
   java.util.Date d1 =(java.util.Date)format.parse(your_Time);
   java.sql.Time ppstime = new java.sql.Time(d1.getTime());
} catch(Exception e) {
   Log.e("Exception is ", e.toString());
}

Discard the date part and use only the time field via GregorianCalendar (to avoid the deprecation warning). 丢弃日期部分,并通过GregorianCalendar仅使用时间字段(以避免过时警告)。

GregorianCalendar timepoint=new GregorianCalendar();
timepoint.setTime(date); // date obtained by parsing
int hours=timepoint.get(Calendar.HOUR_OF_DAY);
int minutes=timepoint.get(Calendar.MINUTE);
int seconds=timepoint.get(Calendar.SECOND);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM