-4

I'm new to Android and Java.

I'm attempting to convert a string with value "1986-10-02" into an Integer so that I can save it to the database. The desired Integer value of that date is 528595200.

I have followed plenty of SO examples but I can't get this to build. Any advice highly appreciated! Here's my code:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+10"));
Date d = sdf.parse("1986-10-02");
Long DateAsInteger = d.getTime()*1000L;
Integer iDOB = DateAsInteger.intValue();

The desired Integer (528595200) is a Unix Timestamp. In another part of my code when I retrieve that integer from the database and convert it into date it works correctly and produces a string = "02-10-1986".

Date date = new Date(cursor.getInt(4)*1000L); // *1000 is to convert seconds to milliseconds
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); // the format of your date
sdf.setTimeZone(TimeZone.getTimeZone("GMT+10"));
String formattedDate = sdf.format(date);
Adam Gatt
  • 31
  • 8
  • 1
    Did you mean: `d.getTime()/1000L` ? – Nir Alfasi Aug 31 '17 at 06:21
  • 1
    Q: What's the error message when you try to build? – paulsm4 Aug 31 '17 at 06:22
  • 1
    Possible duplicate of [Convert Current date as integer](https://stackoverflow.com/questions/12067697/convert-current-date-as-integer) – AskNilesh Aug 31 '17 at 06:23
  • 1
    The `parse()` method throws a checked Exception. You need to surround it with a `try-catch` for `ParseException`. – Mike M. Aug 31 '17 at 06:48
  • dude, preferable all dates are saved in long data type, nont integer –  Aug 31 '17 at 07:03
  • Possible duplicate of [unhandled exception type ParseException](https://stackoverflow.com/questions/11665195/unhandled-exception-type-parseexception) – Ole V.V. Aug 31 '17 at 10:30
  • Maybe more helpful (off-StackOverflow link): https://processing.org/discourse/beta/num_1245180364.html – Ole V.V. Aug 31 '17 at 10:36
  • 1
    Nice that you quote and format your troublesome code in the question, and really nice that you give the expected result. Please (always) also specify exactly how the observed behaviour differs. Quote any error messages verbatim. Then we can guide you much better. “Questions seeking debugging help *("why isn't this code working?")* must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers.” From https://stackoverflow.com/help/on-topic – Ole V.V. Aug 31 '17 at 11:08
  • 1
    Doesn’t your database offer a `date` datatype that is better suited for dates than Unix timestamps are? Such would certainly be more readable if you make ad hoc queries to the database. – Ole V.V. Aug 31 '17 at 13:29

4 Answers4

2

I should like to contribute the modern answer. This isn’t the answer you asked for, but I hope it’s the answer you want.

ThreeTenABP

SimpleDateFormat and Date are long outdated. I can understand why you are still trying to use them on Android, because Android Java 7 comes with nothing better built-in. However, this is a good time for you to learn to use an external library. I recommend you use ThreeTenABP, it offers you the modern Java date and time API, which is much nicer to work with than the outdated classes.

For how to include that library with your project, there is a wonderful explanation in this question: How to use ThreeTenABP in Android Project.

Then the code could be for instance:

    long unixTimestamp = LocalDate.parse("1986-10-02")
            .atStartOfDay(ZoneOffset.UTC)
            .toInstant()
            .getEpochSecond();
    int intValue;
    if (unixTimestamp <= Integer.MAX_VALUE) {
        intValue = (int) unixTimestamp;
        System.out.println(intValue);
    } else {
        System.out.println("int overflow; cannot represent " + unixTimestamp + " in an int");
    }

This prints:

528595200

This is the value you asked for. There seems to be no need to use the time zone of GMT+10 that you tried in your question (I tried, and got the wrong result).

Unix timestamp in an int

Unix timestamps can be represented in 32-bit int until some time in January 2038, after that you will have a kind of “year 2000 problem”. So I guess we might as well get used to using 64-bit long instead.

What went wrong?

For the code in your question, you may have a couple of problems (apart from using the outdated classes):

  1. The compiler requires you to take the possibility of a ParseException into account, either by declaring that your method may throw it, or by surrounding your code with a try/catch construct. Read up on exception handling in Java to learn more, it’s described in a gazillion places.
  2. You multiplied by 1000L instead of dividing by it, thereby overflowing the Integer you tried to store your result into afterwards.
  3. Finally, as I said, you should use TimeZone.getTimeZone("GMT") without +10.
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
1

try this

 try {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+10"));
        Date d = sdf.parse("1986-10-02");
        Log.e("Int Date : ",  d.getTime()/1000+"");// covert date in to int
        Log.e("Int Date : ",""+ new Date(((long)d.getTime()/1000)*1000L));/ covert date in to Long
     } catch (ParseException e) {
        e.printStackTrace();
 }
AskNilesh
  • 67,701
  • 16
  • 123
  • 163
1

Try this dude:

String sDate="31/12/1998";
Date myDate = new Date();
try {
    myDate=new SimpleDateFormat("dd/MM/yyyy").parse(sDate);
} catch (ParseException e) {
    e.printStackTrace();
}
Integer res = (int) myDate.getTime();

may be your problem was because of try catch

0

Many thanks everyone for your help. I follow your advice and am using a Long rather than an Int, and also used a try/catch. I managed to get it to work with the below:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+10"));

try {
         Date d = sdf.parse("1986-10-02");
         Long DateAsInteger = d.getTime()/1000;

     } catch (Exception e) { 

         // this is where you handle it if an error occurs
     }
Adam Gatt
  • 31
  • 8
  • On my computer this yields 528559200. You asked for 528595200. Are you happy? :-) – Ole V.V. Aug 31 '17 at 14:30
  • Details: Use the naming conventions: every variable name should begin with a lowercase letter, so it should be `dateAsInteger`. You don’t need a `Long` object, a primitive `long` (small letter l) is fine for you. Do print a message from the `catch` part so you notice if something goes wrong. Catching `Exception` is considered poor style, better just catch `ParseException`. – Ole V.V. Aug 31 '17 at 14:33