-4

Actually we are using a "timestamp = System.currentTimeMillis()", which is an Epoch time! We are looking to convert the same to normal format ex: 15-03-2020 (dd-mm-yyyy).

We are using:

timestamp = System.currentTimeMillis()
var date = Date(timestamp)
var formattedTime = "$date"

I tried to convert using the above method! I got output as : formatted time is Wed Mar 15 11:32:44 GMT+05:30 2023 I need output as : dd-mm-yyyy hh:mm:ss format, example : 15-03-2023 10:00:00

More precisely the data stored according to the code is some numbers. Example: 1678962531. This number is getting stored in our database. Instead of this number (1678962531) I'm expecting a date to store as yyyy-mm-dd format. Looking a code for this in Kotlin.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • 1
    *didn’t work* is not an error description. Describe wagst is not working and show the code you have tried. – Jens Mar 15 '23 at 05:42
  • https://stackoverflow.com/questions/8237193/how-to-convert-currenttimemillis-to-a-date-in-java this might help you – backdoor Mar 15 '23 at 05:59
  • We are using timestamp = System.currentTimeMillis() var date = Date(timestamp) var formattedTime = "$date" I tried to convert using the above method! I got output as : formatted time is Wed Mar 15 11:32:44 GMT+05:30 2023 I need output as : dd-mm-yyyy hh:mm:ss format, example : 15-03-2023 10:00:00 – Akshay Prakash Mar 15 '23 at 06:16
  • 2
    Don't specify the format to me, specify it to your code. Thats what matters. – experiment unit 1998X Mar 15 '23 at 06:29
  • See [this answer by Sean Patrick Floyd](https://stackoverflow.com/a/4142428/5772882) and [this answer by Basil Bourque](https://stackoverflow.com/a/49378569/5772882). Search for more. – Ole V.V. Mar 15 '23 at 17:56
  • You tagged your question simpledateformat, but you definitely should not use the `SimpleDateFormat` class. It is a notorious troublemaker of a class and fortunately long outdated. Use `DateTimeFormatter` and other classes from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/index.html). – Ole V.V. Mar 15 '23 at 18:02
  • Are you wanting *the time now* in yyyy-mm-dd hh:mm:ss format, or are you wanting to convert a millisecond value obtained from a call to `System.currentTimeMillis()` *at an earlier time*? – Ole V.V. Mar 15 '23 at 18:29
  • Does this answer your question? [convert epoch time to date](https://stackoverflow.com/questions/7740972/convert-epoch-time-to-date) – Ole V.V. Mar 15 '23 at 18:32
  • timestamp = System.currentTimeMillis(), as we are using this. And the data stored according to the code is some numbers, Example : 1678962531. This number is getting stored in our database. Instead of this number (1678962531) I'm expecting a date to store as yyyy-mm-dd format. Looking a code for this in kotlin. – Akshay Prakash Mar 16 '23 at 10:31
  • 1678962531?? Either you have called `System.currentTimeMillis()` on a computer with the clock set to 20 January 1970. Or more likely you have cut off the last three digits before storing to the database, thus converting milliseconds to seconds. In the latter case the time was drawn at 2023-03-16T10:28:51Z (UTC). I can’t write Kotlin, sorry, so hope someone else will help you translate the answers I linked to to Kotlin if needed. – Ole V.V. Mar 16 '23 at 19:04

2 Answers2

2

you could consider directly getting the LocalDateTime instead of getting an epoch using System.currentTimeMillis()

see the following example which does not use parse from this site

import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

    fun main(args: Array) {
    
        val x = LocalDateTime.now()
        val todayFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd") <--change your format here.
        val todayFormatted = x.format(todayFormatter)
    
        println("Today's date is : "+todayFormatted)
    }

if you want to continue using Date() instead, you can check this site and the example they provide

String pattern = "yyyy-MM-dd";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
String date = simpleDateFormat.format(new Date());
System.out.println(date);

And this is what i wrote to simulate an epoch without milliseconds:

        long seconds = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
        System.out.println(seconds);
        LocalDateTime time = LocalDateTime.ofEpochSecond(seconds, 0, ZoneOffset.ofHours(0));
        String formatted = time.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

        System.out.println(formatted);

output:

1679017835  
2023-03-17
  • Correct, but neither the OP nor anyone else should want to use `Date`. That class was poorly designed and is long outdated. Do stick to java.time as for example in your first snippet. – Ole V.V. Mar 15 '23 at 18:05
  • Maybe you will help a bit further? The OP informs us now in a comment that they have got numbers like 1678962531 in their database. Probably seconds since the epoch (not milliseconds). The Java code would be `Instant.ofEpochSecond(1678962531) .atZone(ZoneId.systemDefault()) .format(todayFormatter)`. So if you can write the Kotlin equivalent? – Ole V.V. Mar 16 '23 at 19:11
  • Not really a kotlin equivalent, but you can just call TimeUnit.SECONDS.toMillis(1678962531) to "append" the missing milli seconds and create a proper epoch which can then be passed to the Date() which OP does in his question. This is from the concurrent library `java.util.concurrent.TimeUnit;` – experiment unit 1998X Mar 17 '23 at 01:45
  • 1
    or you could do what i just edited into my answer, using the datetimeformatter from first example – experiment unit 1998X Mar 17 '23 at 02:44
  • Thanks. We should quite obviously prefer the `DateTimeFormatter` solution if available to us (which it is). No one wants a `Date`. – Ole V.V. Mar 17 '23 at 03:18
1

(Using Java syntax, as I’ve not yet learned Kotlin.)

tl;dr

Instant                         // Represents a moment as seen in UTC, that is, with an offset from UTC of zero hours-minutes-seconds.
.ofEpochMilli(
    System.currentTimeMillis()  // Returns a `long` value, a count of milliseconds since the epoch reference of 1970-01-01T00:00Z.
)                               // Returns an `Instant` object.
.atZone( 
    ZoneId.systemDefault() 
)                               // Returns a `ZonedDateTime` object.
.toLocalDate()                  // Returns a `LocalDate` object.
.format(
    DateTimeFormatter
    .ofPattern( "dd-MM-uuuu" )  // Returns a `DateTimeFormatter` object.
)                               // Returns a `String` object.

java.time

timestamp = System.currentTimeMillis()

The method System.currentTimeMillis() returns a count of milliseconds since the epoch reference of the first moment in 1970 in UTC, 1970-01-01T00:00Z.

You can parse that number into an Instant, which represents a moment as seen in UTC as well (an offset from UTC of zero hours-minutes-seconds).

Instant instant = Instant.ofEpochMilli( millisSinceEpoch ) ;

To get that same number:

long millisSinceEpoch = Instant.now().toEpochMilli() ;

Ever better, just stop using System.currentTimeMillis(). Just use Instant in the first place. The Instant class resolves to nanoseconds, though most implementations are constrained to capturing the current moment in microseconds because of the limits of today's computer hardware clocks. Still, that is better that mere milliseconds.

Instant instant = Instant.now() ;  // Likely contains microseconds in Java 9+, though limited to milliseconds in Java 8 (generally).

Your code:

var date = Date(timestamp)

No, no, no. Never use the terrible legacy class java.util.Date nor java.sql.Date. Both were supplanted years ago by the modern java.time classes built into Java 8+, defined by JSR 310. Those two classes were specifically replaced by java.time.Instant and java.time.LocalDate, respectively.

Android 26+ has java.time classes built-in. For earlier Android, the latest tooling provides access to most of the java.time functionality via “API desugaring”.

You said:

convert the same to normal format ex: 15-03-2020 (dd-mm-yyyy)

Determining the date requires a time zone. For any given moment, the date around the world varies by time zone (think about it!).

Apply a time zone (ZoneId) to get a ZonedDateTime.

ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;  // Or perhaps `ZoneId.systemDefault()`.
ZonedDateTime zdt = instant.atZone( z ) ;

Extract the date-only.

LocalDate ld = zdt.toLocalDate() ;

Date-time objects do not have text, so they do not have “format”. You need to generate text in your desired format.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) ;
String output = ld.format( f ) ;
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154