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:

 

posted @ 2019-01-17 09:53  云山之巅  阅读(2536)  评论(0编辑  收藏  举报