Weather App日期转星期异常:仅显示星期四的问题求助
问题排查与修复
你的问题核心是错误地将星期序号传入SimpleDateFormat.format()方法:
dayNumber是Calendar.DAY_OF_WEEK返回的序号(比如周日对应1、周一对应2,依此类推),但SimpleDateFormat.format()方法接收的是Date对象或毫秒级时间戳(long类型),你传入的小整数会被当成时间戳解析,刚好对应固定的星期四,所以才会一直显示同一个结果。
修复方案一:直接格式化Calendar对应的Date对象
不需要单独提取星期序号,直接用Calendar关联的时间来格式化:
var myDate = objData.getString("datetime") var date = SimpleDateFormat("yyyy-MM-dd").parse(myDate) val cal = Calendar.getInstance() cal.time = date val formatter: DateFormat = SimpleDateFormat("EEEE", currentLocale) // 传入cal.time(Date对象)而非dayNumber val dayWeek = formatter.format(cal.time) findViewById<TextView>(R.id.textDay1).text = dayWeek
修复方案二:通过星期序号获取星期名称
如果一定要基于星期序号转换,可以借助DateFormatSymbols:
var myDate = objData.getString("datetime") var date = SimpleDateFormat("yyyy-MM-dd").parse(myDate) val cal = Calendar.getInstance() cal.time = date var dayNumber = cal[Calendar.DAY_OF_WEEK] val symbols = DateFormatSymbols(currentLocale) // weekdays数组索引与Calendar.DAY_OF_WEEK的数值一一对应(1=周日,2=周一...) val dayWeek = symbols.weekdays[dayNumber] findViewById<TextView>(R.id.textDay1).text = dayWeek
更推荐的现代日期API方案
SimpleDateFormat和Calendar是旧版API,存在线程不安全等问题,建议使用Java 8+的java.time系列API(Android 8.0+原生支持,低版本可通过desugar或ThreeTenABP兼容):
import java.time.LocalDate import java.time.format.DateTimeFormatter var myDate = objData.getString("datetime") // 直接解析为LocalDate对象 val localDate = LocalDate.parse(myDate) // 格式化生成星期名称 val dayWeek = localDate.format(DateTimeFormatter.ofPattern("EEEE", currentLocale)) findViewById<TextView>(R.id.textDay1).text = dayWeek
内容的提问来源于stack exchange,提问作者João Oliveira
相关产品推荐
相关产品推荐

