Convert Date Format into Milliseconds
suggest changePass a dd/MM/yyyy string. The formatter is fixed to Locale.US so the pattern does not follow the device locale. A failed parse returns 0. It does not return the current time.
public long getMilliFromDate(String dateFormat) {
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy", Locale.US);
formatter.setLenient(false);
try {
Date date = formatter.parse(dateFormat);
return date.getTime();
} catch (ParseException e) {
e.printStackTrace();
return 0;
}
}
This method converts milliseconds to a timestamp string:
public String getTimeStamp(long timeinMillies) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
String date = formatter.format(new Date(timeinMillies));
System.out.println("Today is " + date);
return date;
}
This method converts a day, month, and year into milliseconds. It is useful with TimePicker or DatePicker. month is 0-based, the same as Calendar and DatePicker (0 is January). The clock time is cleared so the result is midnight in the default time zone.
public static long getTimeInMillis(int day, int month, int year) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, day, 0, 0, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTimeInMillis();
}
It will return milliseconds from date
public static String getNormalDate(long timeInMillies) {
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy", Locale.US);
String date = formatter.format(new Date(timeInMillies));
System.out.println("Today is " + date);
return date;
}
It will return current date
public static String getCurrentDate() {
Calendar c = Calendar.getInstance();
System.out.println("Current time => " + c.getTime());
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy", Locale.US);
String formattedDate = df.format(c.getTime());
return formattedDate;
}
Note: pattern letters are listed in the SimpleDateFormat reference. The link's #number fragment is not a section of that page.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents