英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论