Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

Ganta Hemanth
Ganta Hemanth
6,460 Points

problem with simpledateformat

public String getFormattedString(){
        SimpleDateFormat formatter = new SimpleDateFormat("h:mm a");
        formatter.setTimeZone(TimeZone.getTimeZone(getmTimeZone()));
        Date date = new Date(getMtime() * 1000);
        String timeString = formatter.format(date);
        return timeString;
    }

In the above code, can someone explan the significance of each line in the code? I am confused about what line does what..

1 Answer

Cristian Altin
Cristian Altin
12,165 Points

("h:mm a") one h means to give the hour time without a leading zero (8:00 instead of 08:00). Two ms means to give minutes with a leading zero (you never see 10:9 but always 10:09 for minutes). The a means you are using AM/PM format.

The TimeZone is then chosen or the local one will be used (ppl might not want to know the current time on the other side of the world)

The date is obtained from the number of milliseconds since Jan. 1, 1970 GMT. At first glance I'd say that getMtime() outputs seconds so the * 1000 would be used to convert it to milliseconds in order to get a correct time. Though you read date it really is looking for the time to output.

The final lines format the time just obtained and return it.