Scala “转换字符串”;2013年8月22日“;截止日期格式2013/08/22
这是我在scala中的代码Scala “转换字符串”;2013年8月22日“;截止日期格式2013/08/22,scala,date,date-format,simpledateformat,Scala,Date,Date Format,Simpledateformat,这是我在scala中的代码 var s:String ="22/08/2013" var simpleDateFormat:SimpleDateFormat = new SimpleDateFormat("yyyy-mm-dd"); var date:Date = simpleDateFormat.parse(s); println(date) 日期没有改变。日期格式与2013年8月22日相同,与2013年8月22日相同 如何在scala中将dd/mm/yyyy格式更改为yyyy/
var s:String ="22/08/2013"
var simpleDateFormat:SimpleDateFormat = new SimpleDateFormat("yyyy-mm-dd");
var date:Date = simpleDateFormat.parse(s);
println(date)
日期没有改变。日期格式与2013年8月22日相同,与2013年8月22日相同
如何在scala中将dd/mm/yyyy格式更改为yyyy/mm/dd您需要定义一个
SimpleDataFormat
,它首先解析字符串并从中获取日期。然后将其转换为任何格式
var s:String ="22/08/2013"
var simpleDateFormat:SimpleDateFormat = new SimpleDateFormat("dd/mm/yyyy");
var date:Date = simpleDateFormat.parse(s);
val ans = new SimpleDateFormat("yyyy/mm/dd").format(date)
println(ans)
我试过这个,它对我有效
val s: String = "22/08/2013"
val simpleDateFormat: SimpleDateFormat = new SimpleDateFormat("dd/mm/yyyy")
val date = simpleDateFormat.parse(s)
val df = new SimpleDateFormat("yyyy/mm/dd")
println(df.format(date))
John Vishal的回答中有一个微妙的错误:
mm将08定义为分钟,而不是月份。用MM代替
更正代码:
val s = "2013_08_14"
val simpleDateFormat: SimpleDateFormat = new SimpleDateFormat("yyyy_MM_dd")
val date = simpleDateFormat.parse(s)
val df = new SimpleDateFormat("dd-MMM-yyyy")
println(df.format(date))
最好在scala代码中省略分号。那是首选的款式。也不需要指定字符串等常见类型。@Vishal好的Vishal这是我的错误。。。对于答案,您可能需要查看日期格式化程序教程@Shrey thans这真的很有帮助,备忘录评论:我建议你不要使用SimpleDataFormat
和Date
。这些类设计得很糟糕,而且早已过时,其中前者尤其令人讨厌。而是使用LocalDate
和DateTimeFormatter
,两者都来自。我需要df作为util date如何做到这一点,对不起,我不知道有一个标准的实用程序函数可以在格式之间转换。将不得不编写自定义帮助函数。@zzztimbo您为什么这么认为。如果你看一下回答的时间,我们两人的回答相差1分钟。我也没有复制粘贴其他答案。如果仔细观察,我遵循了Scala惯例,使用val
s而不是var
s@user007对不起,我没有注意到VAL。使用变量是荒谬的。正确的,即使是其他两个答案都有这个错误。无论如何,我们不应该把时间浪费在SimpleDataFormat上。这是一个臭名昭著的麻烦类,而且早已过时。