Yanshof
Yanshof

Reputation: 9926

Fail to save a date object as string

i have 2 button on my application
* button start=> that save 'now' time ( save Date object )
* button end => that also save 'now' time to other object( save Date object )

i see that the object that i saving are OK.

But when i try to produce from this Date object a string i get the time of now and not the time that was save on the 'start date' and 'end date' that i saved before.

The method that i wrote that get Date and create a string ( of time only ) is this:

 public static String ConvertToHourWithMin(Date date){
    String retVal;

    Calendar.getInstance().setTime(date);
    int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
    int min = Calendar.getInstance().get(Calendar.MINUTE);


    retVal = String.format("%s:%s", hour < 10 ? "0" + hour : String.valueOf(hour),
                                    min < 10 ? "0" + min : String.valueOf(min));

    return retVal;
}

On debug i see that the Date parameter is right. But the string that this method is out is not of the date .. its of 'now' time.

what i did wrong ??

Upvotes: 0

Views: 36

Answers (1)

Mike M.
Mike M.

Reputation: 39191

Every time you call Calendar.getInstance(), it returns a new instance with the current time set. You need to keep a reference to the Calendar object that you've set the date on, and get your time from that:

public static String ConvertToHourWithMin(Date date){
    String retVal;

    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    int hour = cal.get(Calendar.HOUR_OF_DAY);
    int min = cal.get(Calendar.MINUTE);

    retVal = String.format("%s:%s", hour < 10 ? "0" + hour : String.valueOf(hour),
                           min < 10 ? "0" + min : String.valueOf(min));

    return retVal;
}

Upvotes: 2

Related Questions