如何在 Scala 中获取当前时间戳作为没有空格的字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48378006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get current timestamp in Scala as a string without spaces?
提问by osk
I want to get for example a string of the current time: "20180122_101043". How can I do this?
例如,我想获取当前时间的字符串:“20180122_101043”。我怎样才能做到这一点?
I can create a val cal = Calendar.getInstance()but I'm not sure what to do with it after.
我可以创建一个,val cal = Calendar.getInstance()但我不确定之后如何处理它。
采纳答案by Sergii Lagutin
Calendaris not the best choice here. Use:
Calendar不是这里的最佳选择。利用:
java.util.Date+java.text.SimpleDateFormatif you have java 7 or belownew SimpleDateFormat("YYYYMMdd_HHmmss").format(new Date)java.time.LocalDateTime+java.time.format.DateTimeFormatterfor java 8+LocalDateTime.now.format(DateTimeFormatter.ofPattern("YYYYMMdd_HHmmss"))
java.util.Date+java.text.SimpleDateFormat如果你有 java 7 或更低版本new SimpleDateFormat("YYYYMMdd_HHmmss").format(new Date)java.time.LocalDateTime+java.time.format.DateTimeFormatter用于 Java 8+LocalDateTime.now.format(DateTimeFormatter.ofPattern("YYYYMMdd_HHmmss"))
回答by prayagupd
LocalDateTimeis what you might want to use,
LocalDateTime是你可能想要使用的,
scala> import java.time.LocalDateTime
import java.time.LocalDateTime
scala> LocalDateTime.now()
res60: java.time.LocalDateTime = 2018-01-22T01:21:03.048
If you don't want default LocalDateTimeformat which is basically ISO formatwithout zone info, you can apply DateTimeFormatteras below,
如果您不想要没有区域信息的LocalDateTime基本上是ISO 格式的默认格式,您可以DateTimeFormatter按如下方式申请,
scala> import java.time.format.DateTimeFormatter
import java.time.format.DateTimeFormatter
scala> DateTimeFormatter.ofPattern("yyyy-MM-dd_HH:mm").format(LocalDateTime.now)
res61: String = 2018-01-22_01:21
Related resource- How to parse/format dates with LocalDateTime? (Java 8)
回答by Sergii Lagutin
You can make use of Java 8 Date/Time API:
您可以使用 Java 8 日期/时间 API:
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
val format = "yyyyMMdd_HHmmss"
val dtf = DateTimeFormatter.ofPattern(format)
val ldt = LocalDateTime.of(2018, 1, 22, 10, 10, 43) // 20180122_101043
ldt.format(dtf)
To get the current time, use LocalDateTime.now().
要获取当前时间,请使用LocalDateTime.now().

