如何从日期字符串中获取周数,输出为2个字符。

huangapple go评论80阅读模式
英文:

How to get the week number from a date string with 2 character output

问题

可以使用以下代码来获得输出结果为 weekNumber: String = 01。在这种情况下,最佳高效方法是什么?

import java.time.format.DateTimeFormatter
import java.time.temporal.WeekFields
import java.util.Locale
import java.time.LocalDate

var dateRangeFrom = "20200101"
var date: java.time.LocalDate = LocalDate.parse(dateRangeFrom, DateTimeFormatter.ofPattern("yyyyMMdd"))

var weekFields: WeekFields = WeekFields.of(Locale.getDefault())
var weekNumber: String = String.format("%02d", date.get(weekFields.weekOfWeekBasedYear()))

Output - weekNumber: String = 01

英文:

I can use the below code to get the output as weekNumber: Int = 1 . But my use case require the output as
weekNumber: String= 01. What should be the best efficient way to do approach this?

import java.time.format.DateTimeFormatter
import java.time.temporal.WeekFields
import java.util.Locale
import java.time.LocalDate

var dateRangeFrom = "20200101"
var date :java.time.LocalDate = LocalDate.parse(dateRangeFrom,DateTimeFormatter.ofPattern("yyyyMMdd"))

var weekFields :WeekFields =  WeekFields.of(Locale.getDefault());
var weekNumber :Int = date.get(weekFields.weekOfWeekBasedYear());

Output - weekNumber: Int = 1

答案1

得分: 2

你可以使用带有模式ww的DateTimeFormatter:

var weekFormat = DateTimeFormatter.ofPattern("ww");
var weekNumber = weekFormat.format(date);

“w”是一年中的周数,“ww”是带有两位数字的一年中的周数(用零填充)。您可以在API文档中查看格式化代码的列表。
https://docs.oracle.com/javase/10/docs/api/java/time/format/DateTimeFormatter.html

英文:

You can use DateTimeFormatter with the pattern ww:

var weekFormat = DateTimeFormatter.ofPattern("ww");
var weekNumber = weekFormat.format(date);

"w" is the week of year, "ww" is week of year with two digits (zero fill). You can see the list of formatting codes in the API documentation.
https://docs.oracle.com/javase/10/docs/api/java/time/format/DateTimeFormatter.html

huangapple
  • 本文由 发表于 2020年4月6日 19:27:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/61058719.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定