Reputation: 617
I have time in milliseconds
, now I want to separate time
and date
from these milliseconds
.
how can i do this???
Upvotes: 14
Views: 28052
Reputation: 166
You can use the Date format and set your millisecond value as a parameter to this constructor, Follow this code:
SimpleDateFormat SDF= new SimpleDateFormat("dd/MM/yyyy");
String date = SDF.format(new Date(millies)));
Upvotes: 0
Reputation: 86369
I suggest java.time, the modern Java date and time API, for your date and time work:
long millisecondsSinceEpoch = 1_567_890_123_456L;
ZonedDateTime dateTime = Instant.ofEpochMilli(millisecondsSinceEpoch)
.atZone(ZoneId.systemDefault());
LocalDate date = dateTime.toLocalDate();
LocalTime time = dateTime.toLocalTime();
System.out.println("Date: " + date);
System.out.println("Time: " + time);
Output in my time zone (Europe/Copenhagen):
Date: 2019-09-07 Time: 23:02:03.456
The date and time classes used in the other answers — Calendar
, Date
and SimpleDateFormat
— are poorly designed and long outdated. This is why I don’t recommend using any of them but prefer java.time.
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
org.threeten.bp
with subpackages.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).Upvotes: 0
Reputation: 188
Further to Kiran Kumar Answer
public static String getFormattedDateFromTimestamp(long timestampInMilliSeconds, String dateStyle){
Date date = new Date();
date.setTime(timestampInMilliSeconds);
String formattedDate=new SimpleDateFormat(dateStyle).format(date);
return formattedDate;
}
Upvotes: 0
Reputation: 890
Convert the milliseconds
to Date
instance and pass it to the chosen formatter:
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
String myDate = dateFormat.format(new Date(dateInMillis)));
Upvotes: 4
Reputation: 12642
you can use like this
Calendar cl = Calendar.getInstance();
cl.setTimeInMillis(milliseconds); //here your time in miliseconds
String date = "" + cl.get(Calendar.DAY_OF_MONTH) + ":" + cl.get(Calendar.MONTH) + ":" + cl.get(Calendar.YEAR);
String time = "" + cl.get(Calendar.HOUR_OF_DAY) + ":" + cl.get(Calendar.MINUTE) + ":" + cl.get(Calendar.SECOND);
Upvotes: 27
Reputation: 9886
Use a Calendar to get the values of different time fields:
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timeInMillis);
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
int monthOfYear = cal.get(Calendar.MONTH);
Upvotes: 3
Reputation: 1212
This function will give you a String date from milliseconds
public static String getFormattedDateFromTimestamp(long timestampInMilliSeconds)
{
Date date = new Date();
date.setTime(timestampInMilliSeconds);
String formattedDate=new SimpleDateFormat("MMM d, yyyy").format(date);
return formattedDate;
}
Upvotes: 21
Reputation: 5636
You could convert the milliseconds to a date object and then extract date in the format of a time string and another string of just the date
Upvotes: 2