我正在使用Dart制作一个简单的活动日历,而我想确定每个月的第一天是哪一天。所以我有这个功能......
int FirstDayOfMonthFallsOnThisDayOfWeek(int year, int month) {
int DayOfWeek = 0;
DateTime theDate = new DateTime(year, month, 1, 0, 0, 0, 0);
DateFormat df = new DateFormat('E');
switch(df.format(theDate).toUpperCase()) {
case "SUNDAY":
DayOfWeek = 1;
break;
case "MONDAY":
DayOfWeek = 2;
break;
case "TUESDAY":
DayOfWeek = 3;
break;
case "WEDNESDAY":
DayOfWeek = 4;
break;
case "THURSDAY":
DayOfWeek = 5;
break;
case "FRIDAY":
DayOfWeek = 6;
break;
case "SATURDAY":
DayOfWeek = 7;
break;
}
return DayOfWeek;
}
要使用DateFormat,我有......
import 'package:intl/date_format.dart';
当然我在pubspec.yaml中导入intl。但是,当我运行这个时,我收到一个错误......
Internal error: '.../dart/cdkCalendar/web/out/packages/intl/date_format.dart':
Error: line 5 pos 6: url expected
part of intl;
这是这个包的错误吗?或者我做错了,我没有看到。此外,如果有人知道一个更好的方法来完成我想要做的事情,那也将非常感激。感谢。
答案 0 :(得分:2)
我不确定为什么会收到错误消息,但这是一个更简单(未经测试)的版本:
int FirstDayOfMonthFallsOnThisDayOfWeek(int year, int month) {
// Use hours != 0 to avoid daylight-saving issues. Shouldn't be a
// problem with the 1st of a month, but still good practice.
return new DateTime(year, month, 1, 12).weekday;
}
答案 1 :(得分:1)
你不需要Intl:
int FirstDayOfMonthFallsOnThisDayOfWeek(int year,int month)=>新的DateTime(年,月,1).weekday;
答案 2 :(得分:0)
好吧,我弄清楚为什么我收到错误 - 我无法导入“部分”。但是,当我尝试导入“intl / intl.dart”时,我遇到了几个错误,所以我假设这个库可能没有完成?无论如何我发现......
DateTime.weekday;
...将返回该月开始的星期几。然而,它从星期一开始为1.我个人发现,因为我见过的每个日历都是星期日开始的,而历史性的星期日是本周的第一天。所以,在任何情况下,我只修改了我的功能,以便纠正从星期日开始的星期几......
int _FirstDayOfMonthDayOfWeek() {
DateTime theDate = new DateTime(_theDate.year, _theDate.month, 1, 0, 0, 0, 0);
return (theDate.weekday == 7) ? 1 : theDate.weekday + 1;
}
答案 3 :(得分:0)
你可以试试这个
List<String> weekdays = [
'Monday',
'Tuesday',
'Wednesday',
'Thurday',
'Friday',
'Saturday',
'Sunday'
];
var now = DateTime.parse(DateTime.now().toString()).weekday;
return weekdays[now];