Location>code7788 >text

java method to get time based on time zone conversion

Popularity:849 ℃/2024-11-16 11:14:09

Method I.

 public static void main(String[] args) {
        // Assuming this is the UTC time string obtained from MySQL
        String utcTimeStr = "2024-09-30T16:00:00Z";
        try {
            // Parsing UTC time strings
            DateTime parsedDateTime = (utcTimeStr);
            // Convert to specified time zone
            DateTime shanghaiDateTime = (parsedDateTime, ("Asia/Shanghai"));
            // Convert to GMT
            DateTime gmtDateTime = (parsedDateTime, ("Etc/GMT"));
            // Formatted output
            ("Formatted output"+shanghaiDateTime);
            // Output GMT time
            ("Output GMT time"+gmtDateTime);
            // Formatted output
            String format1 = (shanghaiDateTime, "yyyy-MM-dd HH:mm:ss");
            String format2 = (gmtDateTime, "yyyy-MM-dd HH:mm:ss");
            // Output converted time string
            ("Formatting [Asia/Shanghai] output"+format1);
            // Output GMT time string
            ("Formatting [Etc/GMT] output"+format2);
        } catch (Exception e) {
            ("Time parsing or conversion failed: " + ());
        }
    }

The console output is as follows:

Formatted output2024-10-01 00:00:00
Output GMT time 2024-09-30 16:00:00
Formatting [Asia/Shanghai]exports2024-10-01 00:00:00
Formatting [Etc/GMT]exports2024-09-30 16:00:00

Method II:

 /**
     * Conversion of a time string to a specified time zone time string
     *@param dateStr time string
     *dateStr@param zoneId Time zone ID
     *zoneId timezoneId@return Specify time zone time string
*/
    private static String timeZoneConvert(String dateStr, String zoneId) {
        DateTime parse = (dateStr);
        ("Original time:{}", parse);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", );
        // Set time zone: e.g. Asia/Shanghai
        ((zoneId));
        String str = (parse);
        ("Time after conversion:{}", str);
        return str;
    }
public static void main(String[] args) {
        // UTC time string converted to a specified time zone time string
        String dateStr = "2024-09-30T16:00:00Z";
        // Time Zone ID
        String zoneId = "GMT+8";
        // time conversion processing
        String dateFormatStr = timeZoneConvert(dateStr, zoneId);
        // Output converted time string
        ("Original time string:" + dateStr);
        // Output converted time string
        ("Converted time string:" + dateFormatStr);
    }

The console output is as follows:

0:54:12.158 [main] INFO .Test05 - Original time:2024-09-30 16:00:00
10:54:12.161 [main] INFO .Test05 - Time after conversion:2024-10-01 00:00:00
The original time string:2024-09-30T16:00:00Z
Converted time string:2024-10-01 00:00:00