问题
I have a String variable in this format "HH:mm".
Lets say the variable value is 05:30.
How would I be able to get those numbers from string and calculate :
(05 * 60 * 60 * 1000) + (30 * 60 * 1000) and put that number (miliseconds) in a new long variable.
Basically I need to convert the String time variable into miliseconds long variable.
回答1:
Let s contain the string of interest. Then e.g. you can say
String s = "5:30";
Pattern p = Pattern.compile("(\\d+):(\\d+)");
Matcher m = p.matcher(s);
if (m.matches()) {
int hrs = Integer.parseInt(m.group(1));
int min = Integer.parseInt(m.group(2));
long ms = (long) hrs * 60 * 60 * 1000 + min * 60 * 1000;
System.out.println("hrs="+hrs+" min="+min+" ms="+ms);
} else {
throw Exception("Bad time format");
}
For what it's worth, there are only 86,400,000 milliseconds in a day, so you don't need the long. An int is big enough.
回答2:
You can use the SimpleDateFormat class
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String inputString = yourTime + ":00.000"; //Added to string to make HH:mm:ss.SSS format
Date date = sdf.parse("1970-01-01 " + inputString);
System.out.println("in milliseconds: " + date.getTime());
回答3:
public static void main(String[] args) throws IOException {
SimpleDateFormat simpleDateFormate = new SimpleDateFormat("HH:mm");
simpleDateFormate.setTimeZone(TimeZone.getTimeZone("UTC"));
String inputString = "05:30";
Date date = null;
try {
date = simpleDateFormate.parse( inputString);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("in millSeconds: " + date.getTime());
long yourvar=date.getTime();
}
Use SimpleDateFormat
来源:https://stackoverflow.com/questions/15561580/android-string-variable-hhmm-to-long-variable-miliseconds