Date java.text.ParseException:不可解析的日期:";一些(2014-05-14T14:40:25.950);
我需要从文件中提取日期。 以下是我的spark计划:Date java.text.ParseException:不可解析的日期:";一些(2014-05-14T14:40:25.950);,date,simpledateformat,datetime-parsing,Date,Simpledateformat,Datetime Parsing,我需要从文件中提取日期。 以下是我的spark计划: import org.apache.spark.sql.SparkSession import scala.xml.XML import java.text.SimpleDateFormat object Active6Month { def main(args:Array[String]){ val format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS")
import org.apache.spark.sql.SparkSession
import scala.xml.XML
import java.text.SimpleDateFormat
object Active6Month {
def main(args:Array[String]){
val format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS")
val format1 = new SimpleDateFormat("yyyy-MM")
val spark = SparkSession.builder.appName("Active6Months").master("local").getOrCreate()
val data = spark.read.textFile("D:\\BGH\\StackOverFlow\\Posts.xml").rdd
val date = data.filter{line => {
line.toString().trim().startsWith("<row")
}}.filter{line=>{
line.contains("PostTypeId=\"1\"")
}}.map{line=>{
val xml = XML.loadString(line)
var closedDate = format1.format(format.parse(xml.attribute("ClosedDate").toString())).toString()
(closedDate,1)
}}.reduceByKey(_+_)
date.foreach(println)
spark.stop
}
}
但它错误地显示了附加到它的字符串“Some”
我的另一个问题是,为什么相同的代码在以下代码中工作:
val date = data.filter{line => {
line.toString().trim().startsWith("<row")
}}.filter{line=>{
line.contains("PostTypeId=\"1\"")
}}.flatMap{line=>{
val xml = XML.loadString(line)
xml.attribute("ClosedDate")
}}.map{line=>{
(format1.format(format.parse(line.toString())).toString(),1)
}}.reduceByKey(_+_)
val date=data.filter{line=>{
line.toString().trim().startsWith(“我猜xml.attribute(“ClosedDate”).toString()
实际上是返回一个字符串,该字符串包含附加到它的部分。您调试过以确保吗
也许您不应该使用toString()
,而是通过使用适当的方法获取属性值
或者,您可以采用“丑陋”的方式,并在模式中包含“一些”:
val format = new SimpleDateFormat("'Some('yyyy-MM-dd'T'hh:mm:ss.SSS')'")
您的第二种方法之所以有效,是因为(这是一个猜测,因为我没有在Scala中编写代码),可能是xml.attribute(“ClosedDate”)
方法返回一个对象,并且在此对象上调用toString()
返回附加了“Some”的字符串(为什么?询问API作者)但是当你在这个对象上使用map
时,它会将行
变量设置为正确的值(没有“Some”部分)。当我将值传递给flatmap,然后在map中打印xml.attribute(“ClosedDate”)的值时,它工作正常。toString()
?它可能返回了一个带有“Some”的字符串“附加到它。是的,它正在返回,但下面的代码工作的原因是:val date=data.filter{line=>{line.toString().trim().startsWith”(“另一个细节是,format1.format
方法已经返回了String
,因此不需要调用toString()
关于它的结果。除非scala在这方面的行为与Java不同……我建议您避免使用SimpleDataFormat
类。它不仅过时很久了,而且还出了名的麻烦。今天我们在这方面做得更好。
val format = new SimpleDateFormat("'Some('yyyy-MM-dd'T'hh:mm:ss.SSS')'")