scala对时间(date)字符串转化为时间戳timestamp的实现

来源:互联网 发布:访客网络怎么开启 编辑:程序博客网 时间:2024/04/29 19:36

在scala编程中,想实现从字符串转化为timestamp的过程中,查找相关资料,才发现资料还是不多。因此在这里将实现过程记录一下。

(注:这种应用情况非常广泛,如从文件中解析某个时间字符串,转化为时间戳再存到HIVE中)


首先写一个转换的函数。

import java.sql.Timestamp
import java.text.SimpleDateFormat
import java.util.Date



     /*
      * change date string to timestamp value
      */
     def getTimestamp(x:String) :java.sql.Timestamp = {
//       "20151021235349"
        val format = new SimpleDateFormat("yyyyMMddHHmmss")
        
        var ts = new Timestamp(System.currentTimeMillis()); 
        try {  
                if (x == "") 
              return null
            else {
              val d = format.parse(x);
              val t = new Timestamp(d.getTime());
              return t
            }
        } catch {  
          case e: Exception => println("cdr parse timestamp wrong")
         } 
        return null
    }

然后进行测试:

        //## test .only gettime can return timestamp value
       var dates = getTimestamp("20151021235349")
       System.out.println(dates.getTime())


在输出结果的时候,还是必须转化为gettime函数才能获得长的时间戳字符串。。

0 0
原创粉丝点击