datetime - 如何从 DateTime Dart 对象获取一年中的某一天、一年中的第几周

标签 datetime dart

我需要从 dart DateTime 对象获取一年中的某一天(day1 是 1 月 1 日)、一年中的星期和月份。

我没有找到任何可用的库。有什么想法吗?

最佳答案

[原始答案 - 请滚动到下面的更新答案,其中包含更新的计算]

一年中的第几周:

/// Calculates week number from a date as per https://en.wikipedia.org/wiki/ISO_week_date#Calculation
int weekNumber(DateTime date) {
  int dayOfYear = int.parse(DateFormat("D").format(date));
  return ((dayOfYear - date.weekday + 10) / 7).floor();
}

其余可通过DateFormat获取(intl package 的一部分)。

[更新的答案] 正如 Henrik Kirk 在评论中指出的那样,最初的答案没有包括对某些日期的必要更正。这是 ISO 周日期计算的完整实现。

/// Calculates number of weeks for a given year as per https://en.wikipedia.org/wiki/ISO_week_date#Weeks_per_year
int numOfWeeks(int year) {
  DateTime dec28 = DateTime(year, 12, 28);
  int dayOfDec28 = int.parse(DateFormat("D").format(dec28));
  return ((dayOfDec28 - dec28.weekday + 10) / 7).floor();
}

/// Calculates week number from a date as per https://en.wikipedia.org/wiki/ISO_week_date#Calculation
int weekNumber(DateTime date) {
  int dayOfYear = int.parse(DateFormat("D").format(date));
  int woy =  ((dayOfYear - date.weekday + 10) / 7).floor();
  if (woy < 1) {
    woy = numOfWeeks(date.year - 1);
  } else if (woy > numOfWeeks(date.year)) {
    woy = 1;
  }
  return woy;
}

关于datetime - 如何从 DateTime Dart 对象获取一年中的某一天、一年中的第几周,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49393231/

相关文章:

python - Pandas:快速将可变数量的月添加到时间戳列

flutter - 如何更改 Flutter snackbar 的高度?

flutter - 如何从 DataTable 小部件 flutter 内的 map 元素列表中渲染数据?

flutter - 从父小部件 flutter 启动和停止秒表

c# - 如何从 Linq to SQL 中的日期时间列获取月份名称?

c# - 使用 Entity Framework 4 和 Linq 查询比较 DateTime 属性中的日期的简单方法

php如何比较一天与近结束时间的比

Python numpy where 函数与日期时间

flutter - Flutter如何像书本一样垂直滚动屏幕

multithreading - 如何同时启动多个 Future 以填充单个 FutureBuilder ListView?