DEF*_*EFL 1 datetime date dart flutter
我需要在 Flutter 中获取周末的日期(仅周五和周六)以及该月的第一天和最后一天的日期
\n这是我周末尝试过的方法,但它不起作用\xc2\xb4t:
\n var dateuntilfriday = DateTime.now();\n\n getFriday() async {\n if (dateuntilfriday.weekday == DateTime.friday) {\n dateuntilfriday.add(Duration(days: 0));\n print("1 Executed");\n } else if (dateuntilfriday.weekday == DateTime.saturday) {\n dateuntilfriday.subtract(Duration(days: 1));\n print("2 Executed");\n } else if (dateuntilfriday.weekday == DateTime.sunday) {\n dateuntilfriday.subtract(Duration(days: 2));\n print("3 Executed");\n } else if (dateuntilfriday.weekday == DateTime.monday) {\n dateuntilfriday.add(Duration(days: 4));\n print("4 Executed");\n } else if (dateuntilfriday.weekday == DateTime.tuesday) {\n dateuntilfriday.add(Duration(days: 3));\n print("5 Executed");\n } else if (dateuntilfriday.weekday == DateTime.wednesday) {\n dateuntilfriday.add(Duration(days: 2));\n print("6 Executed");\n } else if (dateuntilfriday.weekday == DateTime.thursday) {\n dateuntilfriday.add(Duration(days: 1));\n print("7 Executed");\n } else {\n print(\n "and Error Occurent while getting the date for the next or last friday");\n }\n\n print(dateuntilfriday);\n }\nRun Code Online (Sandbox Code Playgroud)\n
我认为这可以实现您所寻求的:
DateTime weekdayOf(DateTime time, int weekday) => time.add(Duration(days: weekday - time.weekday));
DateTime fridayOf(DateTime time) => weekdayOf(time, 5);
DateTime saturdayOf(DateTime time) => weekdayOf(time, 6);
DateTime firstMonthDayOf(DateTime time) => DateTime(time.year, time.month, 1);
DateTime lastMonthDayOf(DateTime time) => DateTime(time.year, time.month + 1, 0);
Run Code Online (Sandbox Code Playgroud)
我在这个月的最后一天使用了一个技巧。[0]下个月的一天是这个月的最后一天。
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
void main() {
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
home: HomePage(),
),
);
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final now = DateTime.now();
final df = DateFormat.yMMMMEEEEd();
return Scaffold(
body: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Today is ${df.format(now)}'),
const SizedBox(height: 16.0),
Text('Friday is ${df.format(fridayOf(now))}'),
const SizedBox(height: 16.0),
Text('Saturday is ${df.format(saturdayOf(now))}'),
const SizedBox(height: 16.0),
Text('First day of month is ${df.format(firstMonthDayOf(now))}'),
const SizedBox(height: 16.0),
Text('Last day of month is ${df.format(lastMonthDayOf(now))}'),
],
),
);
}
}
DateTime weekdayOf(DateTime time, int weekday) => time.add(Duration(days: weekday - time.weekday));
DateTime fridayOf(DateTime time) => weekdayOf(time, 5);
DateTime saturdayOf(DateTime time) => weekdayOf(time, 6);
DateTime firstMonthDayOf(DateTime time) => DateTime(time.year, time.month, 1);
DateTime lastMonthDayOf(DateTime time) => DateTime(time.year, time.month + 1, 0);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1875 次 |
| 最近记录: |