2017-02-24 100 views
0

我有一个字符串,则可能是:字符串匹配时间戳长阶

  1. “未知”
  2. 像时间戳的数字串"1487905455000"
  3. 格式化的日期字符串如"Tue Feb 14 11:27:07 +0800 2017"

我想根据每种情况将其转换为unix时间戳为Long

  1. “未知”将被转移到时间戳的-1
  2. 字符串将被转移到长期价值1487905455000L
  3. 格式化的日期字符串被解析成时间戳

因此,这里是我的想法要做到这一点:

createTimeStamp = { 
    createTimestamp match { 
     case "unknown" => -1L 
     case isDAlldigitas(x) => x.toLong 
     caes _ => { 
      val format = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy") 
      Try(format.parse(_).getTime) match { 
      case Success(t) => t 
      case Failure(_) => -1L 
      } 
     } 
    } 
} 

上面的代码是不工作,但我不知道我这样做是错误的。

回答

2

以下三种情况适用。重要的是第三种情况与有效的变量标识符,如case x

def createTimeStamp(timeStamp: String) = { 
    timeStamp match { 
    case "unknown" => -1L 
    case x if x.replaceAll("\\d", "") == "" => x.toLong 
    case x => 
      val format = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy") 
      Try(format.parse(x).getTime) match { 
       case Success(t) => t 
       case Failure(_) => -1L 
      } 
     } 
    } 
+0

您好,感谢答案替换case _,但如果format.parse(X)产生的异常? – armnotstrong

+0

@armnotstrong我认为我们总是以正确的格式获取数据。现在我已经更新了答案 –

+0

感谢流氓,我发现scala的匹配情况很难理解并且做出最佳实践。再次感谢,我会试试这个 – armnotstrong