Paresh Mayani
Paresh Mayani

Reputation: 128428

Facing problem While Converting Date to MilliSeconds

In my Android Application, I am trying to convert Date/Time to Milliseconds, check the below code:

public long Date_to_MilliSeconds(int day, int month, int year, int hour, int minute)
{

       Calendar c = Calendar.getInstance();
       c.setTimeZone(TimeZone.getTimeZone("UTC"));
       c.set(year, month, day, hour, minute, 00);

        return c.getTimeInMillis();

}

Problem: I am getting 1290455340800(Nov 22 14:49:00 EST 2010) for Nov 22 19:49:00 EST 2010 (i.e. 5 hours back)

FYI, I am Currently in Indian TimeZone, but application can be executed from any country. so How do i exact Convert the date/time into the Milliseconds?

Upvotes: 1

Views: 2588

Answers (5)

neteinstein
neteinstein

Reputation: 17613

I'm using this:

public String timeToString(long time, String format) {
    SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.getDefault());
    sdf.setTimeZone(TimeZone.getDefault());
    return sdf.format(time + TimeZone.getDefault().getRawOffset()
            + TimeZone.getDefault().getDSTSavings());
}

I think it solves the TimeZone problems.

Upvotes: 0

Jim
Jim

Reputation: 22646

This line

c.setTimeZone(TimeZone.getTimeZone("UTC"));

Is probably causing the issue. There is no need to set the TimeZone as the current default is used.

Upvotes: 1

cristis
cristis

Reputation: 1985

The 5 hours difference is the difference between UTC and EST. You can use DateFormat.parse() to parse the input date if it's a string. Or you can use the code above and pass the desired timezone in c.setTimeZone() -- put in EST instead of UTC.

Upvotes: 1

buddhabrot
buddhabrot

Reputation: 1586

In this piece of code, you are getting the amount of milliseconds since 01/01/1970 00:00 in your timezone for Nov 22 19:49:00 EST 2010 in UTC timezone. Why are you setting timezone to UTC?

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499940

My guess is that you're calling Date_to_MilliSeconds(22, 10, 2010, 19, 49). Your code explicitly uses UTC, so it's going to treat whatever you pass it in as UTC.

Just like your previous question (which makes me tempted to close this as a duplicate) it's unclear what you're really trying to do.

If you want to provide a local time to your method, you need to specify a local time zone. If you need to use a local time in the user's time zone, try setting the time zone to TimeZone.getDefault() - although I'd expect that to be the default anyway. If you want to provide a UTC time to your method, you need to specify a UTC time zone (as you are here).

What are you really trying to do?

Upvotes: 1

Related Questions