有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (3) 个答案

  1. # 1 楼答案

    Joda Time library为在多个时区中处理日期/时间提供了一组很好的对象http://joda-time.sourceforge.net/

    举个例子:

        String date = "9/13/2012";
        String time = "5:48pm";
    
        String[] dateParts = date.split("/");
        Integer month = Integer.parseInt(dateParts[0]);
        Integer day = Integer.parseInt(dateParts[1]);
        Integer year = Integer.parseInt(dateParts[2]);
    
        String[] timeParts = time.split(":");
        Integer hour = Integer.parseInt(timeParts[0]);
        Integer minutes = Integer.parseInt(timeParts[1].substring(0,timeParts[1].lastIndexOf("p")));
    
        DateTime dateTime = new DateTime(year, month, day, hour, minutes, DateTimeZone.forID("Etc/GMT"));
        dateTime.withZone(DateTimeZone.forID("Etc/GMT+8"));
    
  2. # 2 楼答案

    爪哇。时间

    java.util日期时间API及其格式化API SimpleDateFormat已经过时且容易出错。建议完全停止使用它们,并切换到modern Date-Time API*

    此外,下面引用的是来自home page of Joda-Time的通知:

    Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.

    使用java.time现代日期时间API的解决方案:

    import java.time.LocalDateTime;
    import java.time.OffsetDateTime;
    import java.time.ZoneOffset;
    import java.time.format.DateTimeFormatter;
    import java.util.Locale;
    
    public class Main {
        public static void main(String[] args) {
            String date = "9/13/2012";
            String time = "5:48pm";
    
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/u h:ma", Locale.UK);
            LocalDateTime ldtSource = LocalDateTime.parse(date + " " + time, dtf);
    
            OffsetDateTime odtSource = ldtSource.atOffset(ZoneOffset.UTC);
            OffsetDateTime odtTarget = odtSource.withOffsetSameInstant(ZoneOffset.of("+08:00"));
    
            System.out.println(odtTarget);
    
            // In a custom format
            System.out.println(odtTarget.format(dtf));
        }
    }
    

    输出:

    2012-09-14T01:48+08:00
    9/14/2012 1:48am
    

    ONLINE DEMO

    Trail: Date Time了解有关现代日期时间API的更多信息


    *无论出于何种原因,如果您必须坚持使用Java 6或Java 7,您可以使用ThreeTen-Backport来支持大部分Java。Java 6&;的时间功能;7.如果您正在为Android项目工作,并且您的Android API级别仍然不符合Java-8,请选中Java 8+ APIs available through desugaringHow to use ThreeTenABP in Android Project

  3. # 3 楼答案

    • 使用设置为UTC时区的SimpleDateFormat解析它
    • 使用设置为感兴趣时区的SimpleDateFormat设置解析的Date值的格式。(很可能不仅仅是“UTC+8”——你应该找出你真正想要的是哪个TZDB时区ID

    例如:

    SimpleDateFormat inputFormat = new SimpleDateFormat("MM/dd/yyyy h:mma", Locale.US);
    inputFormat.setTimeZone(TimeZone.getTimeZone("Etc/UTC");
    Date date = inputFormat.parse(date + " " + time);
    
    // Or whatever format you want...
    SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.US);
    outputFormat.setTimeZone(targetTimeZone);
    String outputText = outputFormat.format(date);
    

    (如果你可以用Joda Time来代替,那就太好了——但我知道它对于Android应用来说相当大。)