在解析客户端日志时常遇到这样的格式:[10/Nov/2016:00:01:02 +0800]
使用Spark(scala)如何对这种格式进行转换,转为“2016-11-18 00:00:00”这样的格式呢,可以使用如下的代码实现
import java.util.{Date, Locale}
import org.apache.commons.lang3.time.FastDateFormat
object ClientLogDateUtils {
val INPUT_TIME_FORMAT = FastDateFormat.getInstance("dd/MMM/yyyy:HH:mm:ss Z",Locale.ENGLISH)
//目标日期格式
val TARGET_FOMAT = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss")
def parseTime(time:String)={
TARGET_FOMAT.format(new Date(getTime(time)))
}
def getTime(time:String) ={
try {
INPUT_TIME_FORMAT.parse(time.substring(time.indexOf("[") + 1, time.lastIndexOf("]"))).getTime()
}catch{
case e :Exception =>{
0L
}
}
}
def main(args: Array[String]): Unit = {
println(parseTime("[10/Nov/2016:00:01:02 +0800]"))
}
}
main中为测试代码
输入的日期格式转换为特定的输出日期格式,如果月份是字母缩写表示时,需加上参数Locale.ENGLISH