Date conversion

前端 未结 4 1282
失恋的感觉
失恋的感觉 2020-12-13 03:05

I have a date variable

var date: Date = new Date()

then I have converted this date to String:

var dateStr = date.toString(         


        
相关标签:
4条回答
  • 2020-12-13 03:08

    Your first try should give you a ClassCastException because you cannot cast.aString to a Date. the second try does not seem to be using the right format that Date.toString() prints. The toString method of java.utility.Date returns a String in the format specified in the javadoc.

    0 讨论(0)
  • 2020-12-13 03:15

    Starting Scala 2.11, targeting Java 8, the java.time Date Time API can be used:

    import java.time.LocalDate
    import java.time.format.DateTimeFormatter
    
    val dtf = DateTimeFormatter.ofPattern("dd-MM-yyyy")
    
    LocalDate.now().format(dtf)        // "06-07-2018"
    LocalDate.parse("06-07-2018", dtf) // java.time.LocalDate = 2018-07-06
    

    Note that:

    • This is part of the standard library (no need for third party dependencies)
    • This is meant to replace the old java.util.Date/SimpleDateFormat api.
    • This is also supposed to replace the widely used joda-time library:

      Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.

    • And by association nscala-time which is a wrapper around joda-time.

    0 讨论(0)
  • 2020-12-13 03:21

    I see a couple of problems in your code, but this works fine:

    scala> val format = new java.text.SimpleDateFormat("dd-MM-yyyy")
    format: java.text.SimpleDateFormat = java.text.SimpleDateFormat@9586200
    
    scala> format.format(new java.util.Date())
    res4: java.lang.String = 21-03-2011
    
    scala> format.parse("21-03-2011")
    res5: java.util.Date = Mon Mar 21 00:00:00 CET 2011
    
    0 讨论(0)
  • using nscala-time the following worked for me :

    import com.github.nscala_time.time._
    import com.github.nscala_time.time.Imports._
    
    val ysterday= (DateTime.now- 1.days).toString(StaticDateTimeFormat.forPattern("yyyyMMdd"))
    
    0 讨论(0)
提交回复
热议问题