2012-03-12 135 views
4

我用安卓:转换日期为毫秒

SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy, HH:mm"); 
String time = formatter.format(new Date()); 

得到的时间(12.03.2012,17:31),现在我想这个时候毫秒转换,因为我有一对夫妇一个文件日期和文字,我希望将日期转换以毫秒为单位,使我不能使用

ContentValues values = new ContentValues(); 
values.put("address", "123"); 
values.put("body", "tekst"); 
values.put("read", 1); 
values.put("date", HERE I MUST PUT A DATE IN MILLISECONDS);  
context.getContentResolver().insert(Uri.parse("content://sms/inbox"), values); 

添加在收件箱中的文本,因为我必须投入毫秒的时间我必须转换的时候,没有人知道如何?

+4

一个简单的谷歌搜索会所做的工作,只是说。 – 2012-03-12 16:40:18

回答

23

最简单的方法是将Date类型转换为毫秒:

SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy, HH:mm"); 
formatter.setLenient(false); 

Date curDate = new Date(); 
long curMillis = curDate.getTime(); 
String curTime = formatter.format(curDate); 

String oldTime = "05.01.2011, 12:45"; 
Date oldDate = formatter.parse(oldTime); 
long oldMillis = oldDate.getTime(); 
+1

你没有理解我,我知道这一点。我想要转换和我有的旧时间,而不是从当前时间获得毫秒。比方说,我有一个时间05.01.2011,12:45,并想要转换它,如何? – Gabrijel 2012-03-12 21:36:02

+0

@Gabrijel好吧,我现在明白了。我更新了我的答案,包括你之后的内容 – 2012-03-13 09:09:38

+0

'long oldMillis = oldDate.getTime()'这只会将'12:45'转换为毫秒,而不是'05.01.2011,12:45'! – 2014-10-23 07:17:34

2

使用你的约会对象,然后调用date.getTime()

0

如果你想在米利斯当前时间只是使用System.currentTimeMillis()

+0

OP不在寻找当前的毫秒数,而是从现有的日期。 – Gangadhar 2012-03-13 07:11:50

0

使用。 getMillis();

e.g:

DateTime dtDate = new DateTime(); 
dtDate.getMillis() 
0
String Date = "Tue Apr 25 18:06:45 GMT+05:30 2017"; 
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy"); 
try { 
    Date mDate = sdf.parse(Date); 
    long timeInMilliseconds = mDate.getTime(); 

} catch (ParseException e) { 
      e.printStackTrace(); 
}