Java milliseconds to calendar

how to get date from milliseconds in android

I have time in milliseconds , now I want to separate time and date from these milliseconds . how can i do this.

@SergeyPekar While that was a good answer back then, it is using the old and poorly designed classes DateFormat , SimpleDateFormat and Calendar . It’s been a very long time since that was recommended.

8 Answers 8

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); 

It is showing wrong month. We’re in April, and I get 3. Also, while using Calendar was a good idea in 2012, it isn’t anymore. We’ve got a lot better in java.time, the modern Java date and time API.

I am late but yea for anyone wondering. if I am not wrong, in the Calendar class, 0 = January and not 1, so it is not showing the wrong month actually. But understandably, it can be confusing.

This function will give you a String date from milliseconds

public static String getFormattedDateFromTimestamp(long timestampInMilliSeconds)

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))); 

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); 

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

Читайте также:  Как освоить html css

i didn’t even mean Date() specifically but no it isn’t, not yet, and not for these purposes. don’t confuse everyone else.

just setTime is not deprecated. other methods (most of them) are deprecated. So why involve Date to just set the time? Why not use Calnedar class

i have no agenda with any specific class. but if some methods are still working fine for what i need and are clearly not deprecated, i don’t throw the baby out with the bathwater.

yes but after setTime . When he is going to retrieve the date..then again he has no option^^ other then using the Calender class. Why not adopt a new born baby!

Further to Kiran Kumar Answer

 public static String getFormattedDateFromTimestamp(long timestampInMilliSeconds, String dateStyle)

java.time and ThreeTenABP

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.

Question: Doesn’t java.time require Android API level 26?

java.time works nicely on both older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
  • Oracle tutorial: Date Time explaining how to use java.time.
  • Java Specification Request (JSR) 310, where java.time was first described.
  • ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
  • ThreeTenABP, Android edition of ThreeTen Backport
  • Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.

Источник

Convert millisecond String to Date in Java

The problem is when i convert the string x to long , some digits go away due to the limit on the size of long. How do I preserve the entire String. THanks.

So your code doesn’t relate to the question at all? — you don’t show the string to long conversion you claim is causing problems.

@John3136: He’s converting the long (milliseconds) into a date and trying to print it «long -> string».

@John3136,&Borleader I am reading a file,so input is String , which i need to convert to long so that I can convert it to date.

Can you post the file reading part? Your code is perfectly fine, the problem must be in the String that you are reading.

5 Answers 5

double tempo=Double.parseDouble(z); 

Why are you parsing your String which is supposed to be a Long as a Double ?

String x = "1086073200000" DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); long milliSeconds= Long.parseLong(x); System.out.println(milliSeconds); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(milliSeconds); System.out.println(formatter.format(calendar.getTime())); 

I tried this code and it worked for me

public static void main(String[] args) < String x = "1086073200000"; long foo = Long.parseLong(x); System.out.println(x + "\n" + foo); Date date = new Date(foo); DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); System.out.println(formatter.format(date)); >

tl;dr

Instant.ofEpochMilli ( 1_346_482_800_000L ); 

Details

The accepted answer by Tim Bender and other answer by enTropy are both correct. You were parsing your input string as a double rather than as a long .

java.time

Also, the Question and Answers are using old outmoded date-time classes. These are now supplanted by the java.time package. See Oracle Tutorial. Much of the java.time functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.

Count from epoch

The java.time classes count from the same epoch as the old classes, first moment of 1970 in UTC. So we can start the same way, with parsing the input as a long .

String input = "1086073200000"; long millis = Long.parseLong ( input ); 

UTC

Use that long number to get an Instant object. This class represents a moment on the time line in UTC, similar in concept to the old java.util.Date . But the new classes have a resolution up to nanoseconds whereas the old are limited to milliseconds. Fortunately the Instant class has a convenient factory method taking a count of milliseconds-since-epoch, ofEpochMilli .

Instant instant = Instant.ofEpochMilli ( millis ); 

Time zone

Now assign a time zone ( ZoneId ) to get a ZonedDateTime object. This is similar in concept to a java.util.Calendar in that it represents a moment on the timeline with a specific assigned time zone.

Always specify the desired/expected time zone. Though optional, never omit the time zone as you did in your use of Calendar in the Question. If omitted, the JVM’s current default time zone is silently applied. This default can vary from machine to machine, and from time to time, even during runtime(!). Better to specify than assume.

ZoneId zoneId = ZoneId.of ( "America/Montreal" ); ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant , zoneId ); 

Dump to console. Notice how the hour-of-day is 07 in UTC but 03 in Québec time as that zone had an offset of -04:00 , four hours behind UTC, during the summer under Daylight Saving Time (DST).

System.out.println ( "input: " + input + " | millis: " + millis + " | instant: " + instant + " | zdt: " + zdt ); 

input: 1086073200000 | millis: 1086073200000 | instant: 2004-06-01T07:00:00Z | zdt: 2004-06-01T03:00-04:00[America/Montreal]

A String is not a date-time

How do I preserve the entire String.

Do not confuse a String of text describing the value of a date-time with the date-time itself. A date-time object can generate a String to represent its value, but that String is separate and distinct from the date-time object.

To generate a String from a java.time object such as ZonedDateTime , either:

  • Call toString to get a String in standard ISO 8601 format.
    (as seen in example code above)
  • Use DateTimeFormatter to:
    (a) Define your own custom format, or
    (b) Automatically localize to the user’s human language and cultural norms.

Search Stack Overflow for many other Questions and Answers on generating formatted Strings from DateTimeFormatter .

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat .

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

  • Java SE 8, Java SE 9, and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
    • See How to use ThreeTenABP….

    The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more.

    Источник

Оцените статью