Scala之Calendar,SimpleDateFormat簡單用法


 1 package com.dingxin.entrance
 2 
 3 import java.text.SimpleDateFormat
 4 import java.util.{Calendar, Date}
 5 
 6 /**
 7   * Created by zhen on 2019/1/16.
 8   */
 9 object SimpleDateFormatTest {
10   def main(args: Array[String]) {
11     val now: Date = new Date()
12     val cal = Calendar.getInstance()
13     val cbzq = "3"
14     val result = if(cbzq == "1"){ //當年1月至當年12月
15       val dateFormat: SimpleDateFormat = new SimpleDateFormat("yyyy-01-01")
16       val begin = dateFormat.format(now)
17 
18       cal.add(Calendar.YEAR,1)
19       val end = dateFormat.format(cal.getTime)
20 
21       begin.toString +"_"+end.toString
22     }else if(cbzq == "2"){ //上年12月至當年12月
23       val dateFormat: SimpleDateFormat = new SimpleDateFormat("yyyy-12-01")
24       val end = dateFormat.format(now)
25 
26       cal.add(Calendar.YEAR,-1)
27       val begin = dateFormat.format(cal.getTime)
28 
29       begin.toString +"_"+end.toString
30     }else if(cbzq == "3") {//上年11月至當年11月
31       val dateFormat: SimpleDateFormat = new SimpleDateFormat("yyyy-11-01")
32       val end = dateFormat.format(now)
33 
34       cal.add(Calendar.YEAR,-1)
35       val begin = dateFormat.format(cal.getTime)
36 
37       begin.toString +"_"+end.toString
38     }else{// 異常
39       ""
40     }
41     println(result)
42     // 根據字符串時間求時間差(天)
43     val dateFormat: SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd")
44     val begin = dateFormat.parse("2019-11-3").getTime
45     val end = dateFormat.parse("2019-12-27").getTime
46     println((end - begin) / (1000 * 60 * 60 * 24))
47   }
48 }
1     // 計算當前年份的總天數
2     val nowCalendar = Calendar.getInstance()
3     val nowDateFormat : SimpleDateFormat = new SimpleDateFormat("yyyy-12-31")
4     val nowEnd = nowDateFormat.parse(nowDateFormat.format(nowCalendar.getTime)).getTime
5     nowCalendar.add(Calendar.YEAR, -1)
6     val nowBegin = nowDateFormat.parse(nowDateFormat.format(nowCalendar.getTime)).getTime
7 
8     println((nowEnd - nowBegin) / (1000 * 60 * 60 * 24))

結果1:

 結果2:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM