如何在dart中获得一周的开始或结束

z9gpfhce  于 2022-12-06  发布在  其他
关注(0)|答案(8)|浏览(195)

如何在dart中找到一周的开始或结束?例如,如果三天前是星期一,今天是星期三,如何使用dart找到一周的开始,即星期一

axkjgtzd

axkjgtzd1#

您可以使用https://api.dart.dev/stable/2.5.1/dart-core/DateTime/weekday.html从DateTime取得工作日,并从您的日期加上/减去这个数字:

void main() {
  final date = DateTime.parse('2019-10-08 15:43:03.887');
  
  print('Date: $date');
  print('Start of week: ${getDate(date.subtract(Duration(days: date.weekday - 1)))}');
  print('End of week: ${getDate(date.add(Duration(days: DateTime.daysPerWeek - date.weekday)))}');
}

DateTime getDate(DateTime d) => DateTime(d.year, d.month, d.day);

更新

请阅读并支持lrn的答案。他对这些东西比我知道得多。:)

xn1cxnb4

xn1cxnb42#

Dart DateTime s有一个weekday getter函数,周一取1,周日取7。

DateTime mostRecentSunday(DateTime date) =>
    DateTime(date.year, date.month, date.day - date.weekday % 7);

获取最近的星期日(如果一周从星期日开始,则为当前周的开始),以及

DateTime mostRecentMonday(DateTime date) =>
    DateTime(date.year, date.month, date.day - (date.weekday - 1));

最近的星期一(如果一周从星期一开始,则星期一为当前周的开始)。
您可以归纳为

/// The [weekday] may be 0 for Sunday, 1 for Monday, etc. up to 7 for Sunday.
DateTime mostRecentWeekday(DateTime date, int weekday) =>
    DateTime(date.year, date.month, date.day - (date.weekday - weekday) % 7);

如果您打算将结果用作日历日期,我将使用DateTime.utc作为构造函数(始终使用UTC作为日历日期,这样您就可以安全地对它们进行基于日期的运算)。
我甚至会考虑在 * 任何 * 情况下使用DateTime.utc,因为它避免了在午夜开始的夏令时的任何潜在问题(很少见,但在时区中,即使是不太可能的事情也会在某个时候发生)。

pokxtpni

pokxtpni3#

具体的操作方式可能取决于应用的本地化程度。如果您希望将星期日视为一周的开始,您可以这样做:

DateTime now = DateTime.now();
int currentDay = now.weekday;
DateTime firstDayOfWeek = now.subtract(Duration(days: currentDay));

如果您将星期一视为开始,请执行以下操作:

DateTime now = DateTime.now();
int currentDay = now.weekday;
DateTime firstDayOfWeek = now.subtract(Duration(days: currentDay - 1));

材料本地化

如果你在Flutter中使用Dart,你可以使用MaterialLocalizations类来获取一周中第一天的索引(0 =星期日,6 =星期六),这将帮助你决定应该使用上面的哪个方法。
firstDayOfWeekIndex属性提供的示例是一个很好的参考:

var localizations = MaterialLocalizations.of(context);
// The name of the first day of week for the current locale.
var firstDayOfWeek = localizations.narrowWeekdays[localizations.firstDayOfWeekIndex];

MaterialLocalizations类提供了大量内置方法来格式化和显示DateTimes。

    • 日期时间**:2021年01月26日11时21分429320秒
  • 格式完整日期:2021年1月26日星期二
  • 格式压缩日期:01/26/2021
  • 格式介质日期:1月26日,星期二
  • 格式短日期:二〇二一年一月二十六日
  • 格式短月天数:一月二十六日
  • 格式月年:二零二一年一月
  • 格式年份:2021

如果这些都不符合您的需要,您也可以使用DateFormat类别来指定DateTime的显示方式。请务必注意,DateFormat类别会以不同的方式来索引日期,其中1 =星期一,7 =星期日。

DateFormat.yMMMd().format(new DateTime.now()) // Jan 26, 2021
DateFormat(DateFormat.ABBR_MONTH_DAY).format(now) // Jan 26
DateFormat(DateFormat.WEEKDAY).format(now) // Tuesday
snz8szmq

snz8szmq4#

FIRST DAY OF THE WEEK

DateTime findFirstDateOfTheWeek(DateTime dateTime) {
    return dateTime.subtract(Duration(days: dateTime.weekday - 1));
}

LAST DAY OF THE WEEK

DateTime findLastDateOfTheWeek(DateTime dateTime) {
    return dateTime
        .add(Duration(days: DateTime.daysPerWeek - dateTime.weekday));
}

LAST DAY OF THE MONTH

DateTime findLastDateOfTheMonth(DateTime dateTime) {
    return DateTime(dateTime.year, dateTime.month + 1, 0);
}

FIRST DAY OF THE MONTH

DateTime findFirstDateOfTheMonth(DateTime dateTime) {
    return DateTime(dateTime.year, dateTime.month, 1);
}

LAST DAY OF THE YEAR

DateTime findLastDateOfTheYear(DateTime dateTime) {
    return DateTime(dateTime.year, 12, 31);
}

FIRST DAY OF THE YEAR

DateTime findFirstDateOfTheYear(DateTime dateTime) {
    return DateTime(dateTime.year, 1, 1); }
zzlelutf

zzlelutf5#

** dart /Flutter -如何找到一周的第一个日期和最后一个日期**

1.查找一周的第一个日期

/// Find the first date of the week which contains the provided date.
DateTime findFirstDateOfTheWeek(DateTime dateTime) {
  return dateTime.subtract(Duration(days: dateTime.weekday - 1));
}

2.查找一周的最后一天

/// Find last date of the week which contains provided date.
DateTime findLastDateOfTheWeek(DateTime dateTime) {
  return dateTime.add(Duration(days: DateTime.daysPerWeek - dateTime.weekday));
}

测试

void main() {
  // Find first date and last date of THIS WEEK
  DateTime today = DateTime.now();
  print(findFirstDateOfTheWeek(today));
  print(findLastDateOfTheWeek(today));

  // Find first date and last date of any provided date
  DateTime date = DateTime.parse('2020-11-24');
  print(findFirstDateOfTheWeek(date));
  print(findLastDateOfTheWeek(date));
}

// Output
2020-11-23 06:54:42.865446
2020-11-29 06:54:42.865446
2020-11-23 00:00:00.000
2020-11-29 00:00:00.000
vsmadaxz

vsmadaxz6#

以上都不适用于我,但@JoeMuller给出了一条关于材料本地化的有趣信息,这让我发现,对于我想要的,周日在日期。工作日应该是0花了一段时间来弄清楚,非常感谢joe和@julemand101我有这个英国日历从周日开始,周六结束

void main() {
   final date = DateTime.parse('2021-08-01');

   print('Date: $date');
   final weekDay =  date.weekday == 7 ? 0 : date.weekday;
   print('Start of week: ${getDate(date.subtract(Duration(days: weekDay)))}');
   print('End of week: ${getDate(date.add(Duration(days: DateTime.daysPerWeek - weekDay - 1)))}');
}

DateTime getDate(DateTime d) => DateTime(d.year, d.month, d.day);
omjgkv6w

omjgkv6w7#

我有两个功能:

DateTime getStartTimeWeek([DateTime? date]) {
  final currentDate = date ?? DateTime.now();
  final dateTime = DateTime(currentDate.year, currentDate.month, currentDate.day);
  return dateTime.subtract(Duration(days: currentDate.weekday - 1));
}

DateTime getEndTimeWeek([DateTime? date]) {
  final currentDate = date ?? DateTime.now();

  final dateTime = DateTime(currentDate.year, currentDate.month, currentDate.day, 23, 59, 59, 999);
  return dateTime.add(Duration(days: DateTime.daysPerWeek - currentDate.weekday));
}
06odsfpq

06odsfpq8#

Below is the code which should work fine in most cases.
We can get start and end of the week like this:-

To get the first day of the week for a date use the below function. Like Sunday (Also known as 7 in WeekDay).
Read lines of comments in code for code clarifications.

DateTime getFirstDayOfWeek({required DateTime currentDateTime}) {
  // Converting date provided to UTC
  // So that all things like DST don't affect subtraction and addition on date
  DateTime dateTimeInUTC = DateTime.utc(
      currentDateTime.year, currentDateTime.month, currentDateTime.day);

  // Getting weekday for the date
  // For reference Sunday weekday is 7 and Friday weekday is 5
  int currentWeekDayInUTC = dateTimeInUTC.weekday;

  // Getting Date for nearest Sunday from the provided date
  // By going back a number of weekdays from the current date to reach Sunday
  DateTime firstDayOfWeekInUTC;
  // If current date is not Sunday subtract days to reach Sunday
  if (currentWeekDayInUTC != DateTime.sunday) {
    firstDayOfWeekInUTC =
        dateTimeInUTC.subtract(Duration(days: currentWeekDayInUTC));
  }
  // If current date is Sunday use it as the first day of week
  else {
    firstDayOfWeekInUTC = dateTimeInUTC;
  }

  // Converting back the date for Sunday from UTC type to Local
  // You can also use UTC type depending on your use case
  DateTime firstDayOfWeekInLocal = DateTime(firstDayOfWeekInUTC.year,
      firstDayOfWeekInUTC.month, firstDayOfWeekInUTC.day);

  if (currentDateTime.isUtc) {
    return firstDayOfWeekInUTC;
  } else {
    return firstDayOfWeekInLocal;
  }
}

To get the last day of the week for a date use the below function. Like Saturday (Also known as 6 in WeekDay).
Read lines of comments in code for code clarifications.

DateTime getLastDayOfWeek({required DateTime currentDateTime}) {
  // Converting date provided to UTC
  // So that all things like DST don't affect subtraction and addition on date
  DateTime dateTimeInUTC = DateTime.utc(
      currentDateTime.year, currentDateTime.month, currentDateTime.day);

  // Getting weekday for the date
  // For reference Sunday weekday is 7 and Friday weekday is 5
  int currentWeekDayInUTC = dateTimeInUTC.weekday;

  // Getting Date for nearest Saturday from the provided date
  // By going forward a number of weekdays from the current date to reach Saturday
  DateTime lastDayOfWeekInUTC;
  // If current date is not Sunday add days enough to reach Saturday
  if (currentWeekDayInUTC != DateTime.sunday) {
    lastDayOfWeekInUTC = dateTimeInUTC
        .add(Duration(days: DateTime.saturday - currentWeekDayInUTC));
  }
  // If current date is Sunday add days UpTo saturday
  else {
    lastDayOfWeekInUTC = dateTimeInUTC.add(Duration(days: DateTime.saturday));
  }

  // Converting back the date for Sunday from UTC type to Local
  // You can also use UTC type depending on your use case
  DateTime lastDayOfWeekInLocal = DateTime(lastDayOfWeekInUTC.year,
      lastDayOfWeekInUTC.month, lastDayOfWeekInUTC.day);

  if (currentDateTime.isUtc) {
    return lastDayOfWeekInUTC;
  } else {
    return lastDayOfWeekInLocal;
  }
}

相关问题