【问题标题】:Getting milliseconds from Date Time Android从日期时间Android获取毫秒
【发布时间】:2017-02-14 18:07:00
【问题描述】:
我正在开发一个 Android 应用程序,我想从日期时间获取毫秒。
我正在使用下面的代码进行解析,但我无法得到正确的结果。
public static long getTimeInMillisecond(String time) {
// eg. time = "27 Sep 2016 12:24PM";
final SimpleDateFormat sdf = new SimpleDateFormat(
"dd MMM yyyy hh:mma");
sdf.setTimeZone(TimeZone.getDefault());
try {
Date mDate = sdf.parse(time);
long timeInMilliseconds = mDate.getTime();
return timeInMilliseconds;
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
【问题讨论】:
标签:
android
date
parsing
time
timezone
【解决方案1】:
public static long getDateStringToLong(String str_date) {
DateFormat formatter;
Date date = null;
formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss", Locale.US);
try {
date = (Date) formatter.parse(str_date);
} catch (ParseException e) {
e.printStackTrace();
}
return date.getTime();
}
根据您的要求更改日期格式
希望这会有所帮助..
【解决方案2】:
你好,你可以试试这个代码..
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String currentDateandTime = sdf.format(new Date());
Log.e("Log","Time----"+currentDateandTime);
【解决方案3】:
终于找到解决办法了:
使用 SimpleDateFormat 添加 Locale.English 并且工作正常。
final SimpleDateFormat sdf = new SimpleDateFormat(
"dd MMM yyyy hh:mma", Locale.ENGLISH);