简体   繁体   中英

android/java -example sunrise sunset calc - changing time from 24hr to 12hr format

Looking at the source code here for this example project: https://github.com/quakig/sunrisesunsettime/tree/master/SunriseSunsetTime

It calculates the sunrise/sunset time. Looking at the code, I cannot see where they determine if the time is returned in 12hour or 24 hours format. Running the sample apk on my phone, it gets returned in 24 hour format.

Where in the code is this determined? or would I be looking in the layout file properties instead of the javascript?

It's located in the transitTime method that is located in the MainActivity :

protected String transitTime(String endtime, String starttime) {
        SimpleDateFormat dt = new SimpleDateFormat("hh:mm");
        Date startTime;
        Date endTime;
        long timdedifferencemillis = 0;
        try {
            startTime = dt.parse(starttime);
            endTime = dt.parse(endtime);
            timdedifferencemillis = endTime.getTime() - startTime.getTime(); // in
                                                                                // milliseconds
        } catch (ParseException e) {
            e.printStackTrace();
        }

        int minutes = Math
                .abs((int) ((timdedifferencemillis / (1000 * 60)) % 60));
        int hours = Math
                .abs((int) ((timdedifferencemillis / (1000 * 60 * 60)) % 24));
        String hm = String.format("%02d h %02d min", hours, minutes);
        return hm;
    }

You will have to tweak it yourself to return the 12hr format.

Joda-Time

You can use the Joda-Time library to alter a time-of-day string from 24-hour format to a 12-hour format.

LocalTime

Unlike the java.util.Date & .Calendar classes bundled with Java, Joda-Time offers a class to represent the time-of-day without a date or time zone. The class is called LocalTime .

In Java 8, the new java.time package (inspired by Joda-Time) also has such a class. But Java 8 technology has not yet been copied in Android. Joda-Time does work in Android.

Example Code

LocalTime localTime = LocalTime.parse( "15:43:21" );
DateTimeFormatter formatter = DateTimeFormat.forPattern( "h:m a" ); // Truncate seconds and fractional seconds.
String output = formatter.print( localTime );

Dump to console.

System.out.println( "output: " + output );  // output: 3:43 PM

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM