正文
在Flutter中,我们可以使用dart语言中的DateTime类来获取本月的开始时间和结束时间。以下是示例代码:
1
2
3
4
5
6
7
|
void getMonthStartEnd() { DateTime now = DateTime.now(); // 获取当前日期时间 DateTime monthStart = DateTime(now.year, now.month, 1 ); // 获取本月第一天的日期时间 DateTime monthEnd = DateTime(now.year, now.month + 1 , 0 , 23 , 59 , 59 ); // 获取本月最后一天的日期时间(时间为23:59:59) print( '本月开始时间:${monthStart.toString()}' ); print( '本月结束时间:${monthEnd.toString()}' ); } |
在上面的示例代码中,我们首先获取当前日期时间,然后使用DateTime类的构造函数获取本月的第一天和最后一天的日期时间。
构造函数的参数依次是年、月、日、时、分、秒。由于本月最后一天的日期可能是28、29、30或31号,根据DateTime类的定义,我们可以将月份加1作为构造函数的第二个参数,然后将日设置为0来获取上一个月的最后一天,从而得到本月的最后一天。
最后,我们使用toString()方法来将日期时间转换为字符串格式输出。
Flutter DateTime 常用操作
在Flutter中,我们可以使用dart语言中的DateTime类进行日期时间的操作。以下是DateTime类的一些常用操作:
1. 获取当前日期时间
1
|
DateTime now = DateTime.now(); |
2. 获取指定日期时间
1
|
DateTime dateTime = DateTime( 2022 , 2 , 22 , 10 , 30 , 0 ); |
3. 获取时间戳
1
2
|
DateTime dateTime = DateTime.now(); int timestamp = dateTime.millisecondsSinceEpoch; |
4. 将时间戳转换为日期时间
1
2
|
int timestamp = 1642678557000 ; DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(timestamp); |
5. 获取日期时间的年、月、日、时、分、秒
1
2
3
4
5
6
7
|
DateTime dateTime = DateTime.now(); int year = dateTime.year; int month = dateTime.month; int day = dateTime.day; int hour = dateTime.hour; int minute = dateTime.minute; int second = dateTime.second; |
6. 获取日期时间是否是闰年
1
2
|
DateTime dateTime = DateTime.now(); bool isLeapYear = dateTime.year % 4 == 0 && dateTime.year % 100 != 0 || dateTime.year % 400 == 0 ; |
7. 获取本月的天数
1
2
|
DateTime dateTime = DateTime.now(); int daysInMonth = DateTime(dateTime.year, dateTime.month + 1 , 0 ).day; |
8. 获取本月的第一天和最后一天
1
2
3
|
DateTime now = DateTime.now(); // 获取当前日期时间 DateTime monthStart = DateTime(now.year, now.month, 1 ); // 获取本月第一天的日期时间 DateTime monthEnd = DateTime(now.year, now.month + 1 , 0 , 23 , 59 , 59 ); // 获取本月最后一天的日期时间(时间为23:59:59) |
9. 格式化日期时间
1
2
|
DateTime dateTime = DateTime.now(); String formattedDate = DateFormat( 'yyyy-MM-dd HH:mm:ss' ).format(dateTime); |
10. 计算日期时间之间的时间差
1
2
3
4
5
6
7
|
DateTime startDate = DateTime( 2022 , 1 , 1 ); DateTime endDate = DateTime( 2022 , 2 , 22 ); Duration difference = endDate.difference(startDate); // 计算时间差 int days = difference.inDays; // 计算相差的天数 int hours = difference.inHours; // 计算相差的小时数 int minutes = difference.inMinutes; // 计算相差的分钟数 int seconds = difference.inSeconds; // 计算相差的秒数 |
以上是DateTime类的一些常用操作,可以根据需求进行使用,更多关于Flutter DateTime 获取时间的资料请关注服务器之家其它相关文章!
原文链接:https://juejin.cn/post/7227828910414413884