Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 我想将此字符串转换为特定日期的日历对象,但它所做的只是给我当前日期_Java_String_Date_Calendar_Simpledateformat - Fatal编程技术网

Java 我想将此字符串转换为特定日期的日历对象,但它所做的只是给我当前日期

Java 我想将此字符串转换为特定日期的日历对象,但它所做的只是给我当前日期,java,string,date,calendar,simpledateformat,Java,String,Date,Calendar,Simpledateformat,我刚刚运行了这段代码,对我来说效果很好startDate.getTime()返回2017年8月1日星期二15:18:01 PDT,这与预期一致。 唯一的问题是在第startDateDate=dateFormat.parse(startDateStr)行的末尾缺少一个分号 这也可能对您有所帮助:tl;博士 遗留类 正如其他人所说,您的代码应该按预期工作 LocalDateTime.parse( "2017/08/01 15:18:01" , DateTimeFormatter.

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

这也可能对您有所帮助:

tl;博士 遗留类 正如其他人所说,您的代码应该按预期工作

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

date.toString():2017年8月1日星期二15:18:01 GMT

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

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

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

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

// 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  ) ;
问题中的示例代码表明,输入字符串表示的日期-时间旨在表示UTC时间(与UTC的偏移量为零)中的一个时刻。上面的
LocalDateTime
对象没有区域或偏移,因此不表示时间线上的点。在指定偏移/分区之前,此对象没有明确的含义

// 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 ) ;
你可以看到

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


对我来说很好-stripQuotes的作用是什么?还应该考虑使用java 8中可用的更新java计时器API。或者任何其他日期/时间API(如JodaTime),您不应该为过时的长类
SimpleDateFormat
Calendar
date
而烦恼
java.time
,现代java日期和时间API,也称为JSR-310,使用起来非常方便。您可以在Java 6和更高版本中使用它(通过Java 6和Java 7)。我认为您的代码无法在11月份生成
startDate
,除非在时钟设置为三个月的计算机上。你能吗?对不起,伙计们,看起来这个特定的代码工作得很好。另一方面,我在另一种方法中使用streams,只需再次给(startdate)/变量当前日期。我不得不使用调试器对其进行排序。非常感谢您的反馈,非常感谢!
// 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 ) ;
// If we assume this date-time was meant to be UTC.
OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC ) ;
System.out.println( "odt.toString(): " + odt ) ;