0

i have a date string in

DD-MM-YYYY (28-11-2011)

I want to convert it into linux time stamp without time or time is zero.

I am doing it by

String dateString="13-09-2011";
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
              Date date = null;
              try {
                    date = (Date)formatter.parse(dateString);
                    Log.v(Constants.LOGGING_TAG, "Date is " + dateString);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                Log.v(Constants.LOGGING_TAG, "Today is " + date.getTime());

but this is not giving the desired result. Any body have any idea to solve this issue.

Shahrukh A.
  • 1,071
  • 3
  • 11
  • 20
  • 1
    "not giving the desired result" isn't very precise. Please tell us what you're getting and what you expected. – Jon Skeet Nov 28 '11 at 06:01
  • i provide the dateString = 28-11-2011 and it gives me 1322420400000. When i reconvert 1322420400000 to date, i got Sun, 27 Nov 2011 19:00:00 GMT. – Shahrukh A. Nov 28 '11 at 06:06

1 Answers1

3

It's not clear what the problem is as you haven't told us what you expected and what you're getting, but I suspect there are two potential problems:

  • You haven't specified a time zone, so the formatter will parse the value in the system local time zone. If you want a date only, you should probably set the formatter to UTC first:

    formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    
  • If you want a Unix time value (in seconds), you'll need to divide the value in Date by 1000, as java.util.Date is represented in milliseconds:

    long seconds = date.getTime() / 1000;
    

I'd also thoroughly recommend using Joda Time instead of the built-in classes for date/time manipulation.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • +1 for the Joda-Time link, thanks Jon - why the heck haven't I found that before?!? Coming from Smalltalk to Java (long, long ago), I've always complained about how silly and unintuitive the Java Date implementation is. – Amos M. Carpenter Nov 28 '11 at 06:45