Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.