如何仅更改DateTime中的时间? [英] How to only change the time in DateTime?

查看:65
本文介绍了如何仅更改DateTime中的时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a DateTime and I'm trying to do two things with it. 1: Only update the date and month. 2: Only update the time. How can I achieve that?

  DateTime currentDateTime = DateTime.now();

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

有什么办法可以破坏 currentDateTime ,例如 DateTime(... currentDateTime,..newTime)

Is there any way I can destruct the currentDateTime like DateTime(...currentDateTime, ..newTime)

推荐答案

从Datetime.now()属性而不是整个Datetime.now()对象构造Datetime对象.这应该起作用.

Construct your Datetime object from Datetime.now() properties, instead of the whole Datetime.now() object. This should work.

  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的构造函数是这样的

Remember the constructor of Datetime looks like this

DateTime(int year, [int month = 1, int day = 1, int hour = 0, int minute = 0, int second = 0, int millisecond = 0, int microsecond = 0])

这篇关于如何仅更改DateTime中的时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆