You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter及Dart中获取当前星期几?

在Flutter/Dart中获取当前星期几(如"Tuesday")

嘿,我懂你想要的那种便捷调用方式!Dart的DateTime类本身没有内置getCurrentDay()方法,但我们可以轻松实现你要的效果,甚至封装成你期望的语法形式~

方法1:使用intl包(推荐,支持多语言)

首先需要在pubspec.yaml里添加intl依赖:

dependencies:
  intl: ^0.18.1 # 建议使用最新版本

然后就可以用DateFormat直接格式化出完整的星期名称:

import 'package:intl/intl.dart';

void main() {
  // 获取当前时间实例
  final now = DateTime.now();
  // 格式化得到完整星期名称(比如"Tuesday")
  final dayName = DateFormat('EEEE').format(now);
  print(dayName);
}

方法2:封装成你想要的DateTime.getCurrentDay()形式

如果你想直接用var day = DateTime.getCurrentDay();这种调用方式,可以给DateTime扩展一个静态方法:

import 'package:intl/intl.dart';

// 给DateTime类扩展自定义方法
extension DateTimeDayExtension on DateTime {
  static String getCurrentDay() {
    return DateFormat('EEEE').format(DateTime.now());
  }
}

// 使用示例
void main() {
  var day = DateTime.getCurrentDay();
  print(day); // 输出:Tuesday(根据当前实际日期)
}

方法3:不依赖第三方包(纯Dart实现)

如果你不想引入intl包,可以自己维护一个星期名称列表,通过weekday属性映射:

// 给DateTime类扩展自定义方法
extension DateTimeDayExtension on DateTime {
  static String getCurrentDay() {
    // 注意:DateTime.weekday返回1=Monday,7=Sunday,所以列表索引对应调整
    const dayNames = [
      'Sunday',
      'Monday',
      'Tuesday',
      'Wednesday',
      'Thursday',
      'Friday',
      'Saturday'
    ];
    return dayNames[DateTime.now().weekday % 7];
  }
}

// 使用示例
void main() {
  var day = DateTime.getCurrentDay();
  print(day); // 输出对应星期名称
}

这样就能完美实现你想要的效果啦!

内容的提问来源于stack exchange,提问作者the coder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:36:24