有 Java 编程相关的问题?

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

java我想将这个字符串转换成特定日期的日历对象,但它所做的只是给我当前日期

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

        String startDateStr = stripQuotes("2017/08/01 15:18:01"); 

                    Date startDateDate; 
                    Calendar startDate = null;
                    try {
                        startDateDate = dateFormat.parse(startDateStr)
                        startDate = Calendar.getInstance(); 
                        startDate.setTime(startDateDate);               
                    } catch (ParseException ex) {
                        Logger.getLogger(AttendanceController.class.getName()).log(Level.SEVERE, null, ex);
                    }


Honey honey1 = new Honey(1,"ok","ok2",startDate);

共 (2) 个答案

  1. # 1 楼答案

    我刚刚运行了这个代码,对我来说效果很好startDate.getTime()返回Tue Aug 01 15:18:01 PDT 2017,这与预期一致。 唯一的问题是startDateDate = dateFormat.parse(startDateStr)行末尾缺少一个分号

    这也可能对您有所帮助:Set the Calendar to a specific date

  2. # 2 楼答案

    tl;博士

    LocalDateTime.parse( 
        "2017/08/01 15:18:01" , 
        DateTimeFormatter.ofPattern( "uuuu/MM/dd HH:mm:ss" , Locale.US )
    ).atOffset( ZoneOffset.UTC )
    

    遗留类

    正如其他人所说,您的代码应该按预期工作

    // Old outmoded way using troublesome legacy classes.
    SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Date date = format.parse( input ) ;
    Calendar cal = Calendar.getInstance() ;
    cal.setTime( date ) ;
    System.out.println( "date.toString(): " + date  ) ;
    

    你可以看到code run live at IdeOne.com

    date.toString(): Tue Aug 01 15:18:01 GMT 2017

    你有更大的问题。您正在使用非常麻烦的旧日期时间类,这些类现在是遗留的,被java取代。时间课。避免像瘟疫一样的旧课程

    ISO 8601

    顺便说一句,您正在使用一种不太理想的格式来将日期时间表示为字符串。而是使用标准的ISO 8601格式。爪哇。时间类在解析/生成字符串时默认使用ISO 8601格式。你可以在下一个例子中看到

    并指定一个时区。忽略偏移或区域会导致混乱、错误和痛苦

    爪哇。时间

    让我们用现代的方式重写代码

    // New modern way in Java 8 and later.
    DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu/MM/dd HH:mm:ss" , Locale.US ) ;
    LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
    

    问题中的示例代码表明,输入字符串表示的日期时间是用来表示UTC时间的一个时刻(与UTC的偏移量为零)。我们上面的LocalDateTime对象没有区域或偏移,因此代表时间线上的一个点。在指定偏移/分区之前,此对象没有明确的含义

    // If we assume this date-time was meant to be UTC.
    OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC ) ;
    System.out.println( "odt.toString(): " + odt ) ;
    

    你可以看到code run live at IdeOne.com

    odt.toString(): 2017-08-01T15:18:01Z