You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Dart的DateTime对象获取年积日、年周数及年月份?

在Dart中获取DateTime的年积日、年周数和年月份

嘿,这个需求我之前也折腾过!Dart标准库确实没有直接提供这些现成的方法,但完全可以自己实现,不用依赖额外的重型库,下面给你逐个解决:

1. 年积日(Day of Year,1月1日为第1天)

核心思路是计算当前日期和当年1月1日的天数差,再加1(因为1月1日本身是第1天)。要注意时区问题,如果你的DateTime是本地时间,就要用本地时间的1月1日;如果是UTC时间,就用UTC的1月1日。

示例代码:

int getDayOfYear(DateTime date) {
  final startOfYear = DateTime(date.year, 1, 1, date.hour, date.minute, date.second, date.millisecond, date.microsecond, isUtc: date.isUtc);
  return date.difference(startOfYear).inDays + 1;
}

// 使用示例
final now = DateTime.now();
print(getDayOfYear(now)); // 比如2024年5月20日会输出141

2. 年周数(Week of Year)

这里要注意周编号的规则,最常用的是ISO 8601标准:周一为一周的第一天,当年的第一周必须包含至少4天(也就是说,1月1日如果在周一到周四,那就是第一周;如果在周五到周日,那属于上一年的最后一周)。

实现这个可以用以下方法:

int getIsoWeekOfYear(DateTime date) {
  // 保持原时区或转UTC,根据你的需求调整
  final d = date.isUtc ? date : date.toUtc();
  final dayOfYear = getDayOfYear(d);
  final weekday = d.weekday; // 1=周一,7=周日

  // 计算当年第一个周一的日期
  final firstDayOfYear = DateTime(d.year, 1, 1, isUtc: true);
  int firstMondayOffset = (1 - firstDayOfYear.weekday + 7) % 7;
  final firstMonday = firstDayOfYear.add(Duration(days: firstMondayOffset));

  if (d.isBefore(firstMonday)) {
    // 属于上一年的最后一周
    return getIsoWeekOfYear(DateTime(d.year - 1, 12, 31, isUtc: true));
  } else {
    final daysSinceFirstMonday = d.difference(firstMonday).inDays;
    return (daysSinceFirstMonday ~/ 7) + 1;
  }
}

// 使用示例
final now = DateTime.now();
print(getIsoWeekOfYear(now)); // 比如2024年5月20日是第21周

如果不需要严格的ISO标准,只是简单按周日或周一开始算第一周,那可以简化计算,比如调整weekday的偏移即可。

3. 年月份

如果是要获取带年份的月份表示(比如"2024-05"这样的字符串),可以直接拼接实现:

String getYearMonthString(DateTime date) {
  final year = date.year.toString();
  final month = date.month.toString().padLeft(2, '0');
  return '$year-$month';
}

// 使用示例
final now = DateTime.now();
print(getYearMonthString(now)); // 输出类似"2024-05"

如果你只是需要获取年份和月份的数值,那DateTime本身就有date.year和date.month属性,直接调用就行啦!


内容的提问来源于stack exchange,提问作者fvisticot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:09:07