-1

I want to convert the date and time received from the system into a integer in Android Studio with Java

For example

System Date/Time: 2021-06-18 19:51:43 --> Convert to :1624029703

please guide me

Dr.NINJS
  • 7
  • 2
  • 2
    Have you tried anything? You really need to make some effort to search first. The question in my comment below was found in < 10 seconds. – tnw Sep 09 '21 at 16:38
  • 2
    An `int` does not have enough bits to store a date and time, a `long` has enough bits to store the number of milliseconds since the Unix epoch, but I don't think it can hold the time zone as well. – Jonny Henly Sep 09 '21 at 16:39
  • 2
    What did your search bring up? Mine found for example [How to Convert Timestamp String to Unix Time (Epoch) in Java](https://phpfog.com/how-to-convert-timestamp-to-unix-time-epoch-in-java/). Please learn that you’re supposed to search before posting a question here. – Ole V.V. Sep 09 '21 at 17:33
  • Don’t use `SimpleDateFormat`, `Calendar` nor `Date`. Use java.time, the modern Java date and time API. `LocalDateTime.parse("2021-06-18 19:51:43", DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss")).atZone(ZoneId.of("Asia/Tehran")).toEpochSecond()` yields 1624029703. – Ole V.V. Sep 09 '21 at 20:00
  • 1
    @JonnyHenly I was thinking the same. However (1) a `long` counts as a kind of integer too (the OP only asked for an integer, not an `int`). (2) Until 2038, so the next 15+ years, a 32 bits `int` will suffice. We shouldn’t settle with that, of course, we should future-proof our code. – Ole V.V. Sep 10 '21 at 20:13

1 Answers1

1

You can create a method dateConverter() that accept a String

public static long dateConverter(String date) {
        DateTimeFormatter dateFormatter
                = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        return LocalDate.parse(date, dateFormatter)
                .atStartOfDay(ZoneOffset.UTC)
                .toInstant()
                .toEpochMilli();

    }

DateTimeFormatter is a replacement for the old SimpleDateFormat.

You can then call this method from the main.

public class Main {

    public static void main(String[] args) {

        long longDate = dateConverter("2021-06-18 19:51:43");


        System.out.println("Long Date is: " + longDate);

    }
Tonnie
  • 4,865
  • 3
  • 34
  • 50