Android将日期和时间转换为毫秒

我有一个日期和时间格式如下:

Tue Apr 23 16:08:28 GMT+05:30 2013 

我想转换成毫秒,但实际上我不知道它是哪种格式。 任何人都可以帮助我。

使用以下方法

 String givenDateString = "Tue Apr 23 16:08:28 GMT+05:30 2013"; SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy"); try { Date mDate = sdf.parse(givenDateString); long timeInMilliseconds = mDate.getTime(); System.out.println("Date in milli :: " + timeInMilliseconds); } catch (ParseException e) { e.printStackTrace(); } 

详细了解日期和时间模式字符串 。

尝试这个…

 Calendar calendar = Calendar.getInstance(); calendar.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth(), timePicker.getCurrentHour(), timePicker.getCurrentMinute(), 0); long startTime = calendar.getTimeInMillis(); 
  **You can use this code** long miliSecsDate = milliseconds ("2015-06-04"); Log.d("miliSecsDate", " = "+miliSecsDate); public long milliseconds(String date) { //String date_ = date; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); try { Date mDate = sdf.parse(date); long timeInMilliseconds = mDate.getTime(); System.out.println("Date in milli :: " + timeInMilliseconds); return timeInMilliseconds; } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return 0; } 
 Date beginupd = new Date(cursor1.getLong(1)); 

此variablesbeginupd包含格式

 Wed Oct 12 11:55:03 GMT+05:30 2011 long millisecond = beginupd.getTime(); Date.getTime() JavaDoc states: 

返回自此Date对象表示的1970年1月1日00:00:00 GMT以来的毫秒数。

将日期和时间字符串隐藏到毫秒:

  public static final String DATE_TIME_FORMAT = "MM/dd/yyyy HH:mm:ss a"; 

要么

  public static final String DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss"; 

要么

  public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"; //TimeZone.getAvailableIds() to list all timezone ids String timeZone = "EST5EDT";//it can be anything timezone like IST, GMT. String time = "2/21/2018 7:41:00 AM"; public static long[] convertTimeInMillis(String dateTimeFormat, String timeZone, String... times) throws ParseException { SimpleDateFormat dateFormat = new SimpleDateFormat(dateTimeFormat, Locale.getDefault()); dateFormat.setTimeZone(TimeZone.getTimeZone(timeZone)); long[] ret = new long[times.length]; for (int i = 0; i < times.length; i++) { String timeWithTZ = times[i] + " "+timeZone; Date d = dateFormat.parse(timeWithTZ); ret[i] = d.getTime(); } return ret; } 

// millis到dateString

  public static String convertTimeInMillisToDateString(long timeInMillis, String DATE_TIME_FORMAT) { Date d = new Date(timeInMillis); SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); return sdf.format(d); } 

在Kotlin,

只是用

 timeInMilSeconds = date.time 

其中timeInMilSeconds是毫秒( var timeInMilSeconds: Long ), date是Date

在Kotlin试试这个,

 val calendar = Calendar.getInstance() val UniqueID = calendar.timeInMillis 

Java中的相同代码,

 Calendar calendar = Calendar.getInstance(); long time = calendar.getTimeInMillis();