当前位置: 首页 > 知识库问答 >
问题:

如何只更改DateTime中的时间?

鲁浩言
2023-03-14

我有一个DateTime,我正在尝试用它做两件事。1:只更新日期和月份。2:只更新时间。我如何实现这一点?

  DateTime currentDateTime = DateTime.now();

  void updateTime(DateTime newTime) {
       currentDateTime = ?
  }
  void updateDate(DateTime newTime) {
       currentDateTime = ?
  }

有什么方法可以破坏< code>currentDateTime像< code>DateTime(...当前日期时间,..newTime)

共有2个答案

仰翰采
2023-03-14

要仅更新时间,您可以使用星期几。这是我能做到的方法

DateTime currentDateTime = DateTime.now();

void updateTime(TimeOfDay newTime) {
  // 2020-09-07 09:03:24.469
  TimeOfDay time = TimeOfDay(hour: newTime.hour, minute: newTime.minute);
  currentDateTime = DateTime(currentDateTime.year, currentDateTime.month, currentDateTime.month, time.hour, time.minute);
  // 2020-09-09 15:00:00.000
}

void updateDate(DateTime newTime) {
  // 2020-09-09 15:00:00.000
  currentDateTime = DateTime(newTime.year, newTime.month, newTime.day);
  // 2021-01-01 00:00:00.000
}

我希望这是有帮助的。

闽念
2023-03-14

从日期时间()属性构造日期时间对象,而不是整个日期时间()对象。这应该有效。

  DateTime currentDateTime = DateTime.now();

  void updateTime(DateTime currentDateTime, DateTime newTime) {
       currentDateTime = DateTime(
         year: currentDateTime.year,
         month: currentDateTime.month
         day: currentDateTime.day,
         hour: newTime.hour,
         minute: newTime.minute,
         second: newTime.second,
       );
  }

  void updateDate(DateTime currentDateTime, DateTime newDate) {
       currentDateTime = DateTime(
         year: currentDateTime.year,
         month: newTime.month
         day: newTime.day,
         hour: currentDateTime.hour,
         minute: currentDateTime.minute,
         second: currentDateTime.second,
       );
  }

请记住Datetime的构造函数如下所示

DateTime(int year, [int month = 1, int day = 1, int hour = 0, int minute = 0, int second = 0, int millisecond = 0, int microsecond = 0])
 类似资料:
  • 我有一个带有读数的数据库集合,每个新读数都需要检查,如果它不寻常,如果是,则需要发送警报。 所以我使用

  • 我正在使用Spring Data MongoDB和Spring Data Rest创建一个Rest API,它允许对我的MongoDB数据库进行GET、POST、PUT和DELETE操作,除了更新操作(PUT)之外,其他操作都很好。只有当我在请求体中发送完整的对象时,它才起作用,否则变量没有在rquest中发送它,则为NULL。有人能指导我解决这个问题吗。

  • 我制作了一个带有路由器dom的网站,不幸的是URL发生了变化,我需要刷新页面以查看正确的组件。 我已经看到了StackOverflow上的所有线程,但没有一个对我有帮助。 所以,我有一个pp.js作为主容器: 在标题我有链接: 到App.js我导入路由器、交换机和路由。为了header.js我导入路由器和链接。 所有内容都通过标准ReactDOM.render(,document.getEleme

  • 数据库中的DATE字段具有以下格式: 我想从日期中删除时间并返回如下日期:

  • 问题内容: 我有一张桌子,桌子上有个日期 creationDate 。像这样存储时间戳 实际上,我正在使用mysql2sqlite.sh脚本将数据库从mysql转换为sqlite。并且在转换数据库时,它从creationDate列中减少了5:30的时间。这可能是 格林尼治标准时间的 问题。 因此,现在我想更新时间戳,并向creationDate列中的每个条目添加5小时30分钟。 我搜索了很多,但没

  • 我正在使用FluentD(v.12最后一个稳定版本)向Kafka发送消息。但是FluentD正在使用一个旧的KafkaProducer,所以记录时间戳总是设置为-1。因此,我必须使用WallclockTimestampExtrator将记录的时间戳设置为消息到达kafka时的时间点。 是否有特定于Kafka Streams的解决方案? 我真的感兴趣的时间戳,是由Fluentd在消息中发送的: “时