Yahor Urbanovich
Yahor Urbanovich

Reputation: 773

Get Unix time from TextView

I have TextView with time: HH:mm:ss:ms For example I have time: 00:20:03:19. My function returns -9596 How to convert this time to unix time? where is the mistake? Thanks.

 private long convertStringToUnixTime() throws ParseException {
    String dateStr = "00:20:03:19";
    long unixTime;

    DateFormat formatter = new SimpleDateFormat("HH:mm:ss:ms");
    unixTime = formatter.parse(dateStr).getTime();

    unixTime = unixTime / 1000;

    return unixTime;
}

Upvotes: 0

Views: 49

Answers (2)

OneCricketeer
OneCricketeer

Reputation: 191738

This returns 22803019 - which is the milliseconds since epoch.

new SimpleDateFormat("HH:mm:ss:SSS").parse("00:20:03:19").getTime()

You didn't say whether you wanted seconds or milliseconds, but since you are parsing milliseconds, I guess you want the later, so no need to divide.

All in all, your method could be much shorter if you give the String as the parameter

private long convertStringToUnixTime(String dateStr) throws ParseException {
    return new SimpleDateFormat("HH:mm:ss:SSS").parse(dateStr).getTime();
}

Upvotes: 2

fechidal89
fechidal89

Reputation: 723

The Milliseconds is 'S'. And It is three. Your format should be as "HH:mm:ss:SSS".

More information here: SimpleDateFormat

Upvotes: 0

Related Questions