Saturday, May 11, 2013

Android programming - How to convert a date string to a date as milisecond value

Here is a function to convert a date string to a date as a millisecond value. The value is the number of milliseconds since Jan. 1, 1970, midnight GMT.

public long longDate (String sdate){
  
  long longDate = System.currentTimeMillis(); //Initializes var with current time in case parsing fails
   
  SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy, HH:mm", Locale.US); //Describes date pattern
  format.setLenient(false); //enforces strict pattern matching  
    
  try {
   Date date = format.parse(sdate); //converts string to a date object
   longDate = date.getTime(); 
  } catch (ParseException e) {
  }
    
  return longDate;  
  }


So basically you would call the function like longDate (11/05/2013, 22:25).

5 comments: