【问题标题】:Groovy/Grails date class - getting day of monthGroovy/Grails 日期类 - 获取月份中的日期
【发布时间】:2009-09-06 13:28:13
【问题描述】:

目前我正在使用以下代码在 Groovy 中获取年、月、日、小时和分钟:

Date now = new Date()
Integer year = now.year + 1900
Integer month = now.month + 1
Integer day = now.getAt(Calendar.DAY_OF_MONTH) // inconsistent!
Integer hour = now.hours
Integer minute = now.minutes
// Code that uses year, month, day, hour and minute goes here

在这种情况下,使用getAt(Calendar.DAY_OF_MONTH) 表示月份中的某天似乎有点不一致。有没有更短的方法来获得一个月中的哪一天?

【问题讨论】:

  • 你为什么现在.year + 1900?
  • Mykola: new Date().year 目前是 109,因此需要加上 1900。
  • 但是为什么你把它加到某个“年份”而不使用它呢?
  • 年、月、日、小时和分钟在后面的代码中使用。
  • 毫秒或微秒呢?我试过 now.milliseconds 或 microseconds 但没有这样的属性

标签: grails groovy


【解决方案1】:

如果您将以下内容添加到代码中,则应将月份中的日期分配给日期整数:

Integer day = now.date

这是一个独立的例子:

def now = Date.parse("yyyy-MM-dd", "2009-09-15")
assert 15 == now.date

【讨论】:

  • 谢谢!我不知道我怎么会错过它!
  • 也许你因为糟糕的 API 错过了它!
【解决方案2】:

不是所有这些行都是垃圾吗? 以下两行在 groovysh 中完成了这项工作

date = new Date()
date.getAt(Calendar.DAY_OF_MONTH)

在你的真实代码中而不是在控制台中使用它

def date = new Date()
def dayOfMonth = date.getAt(Calendar.DAY_OF_MONTH)

【讨论】:

  • 这段代码在 groovysh 控制台上给了我 6。如果这是您想要的,那么这就是答案。
  • 问题是没有获取月份的日期。问题在于以一致的方式进行。
  • “垃圾”其实是问题的上下文
【解决方案3】:

你做它的方式是唯一的方法。 java date 对象存储月份和日期,但不存储任何信息,例如给定月份的长度或您所在月份的哪一天。您需要使用 Calendar 类来查找大量此类信息。

【讨论】:

    【解决方案4】:

    您可以像这样从 Groovy 中的 Date 获取一个月中的某一天:

    ​Date date = new Date()
    int dayOfMonth = date[Calendar.DAY_OF_MONTH]
    

    【讨论】:

      【解决方案5】:

      这个版本相当简洁:

      Calendar.instance.get(Calendar.DAY_OF_MONTH)
      

      【讨论】:

      • 绝对可以,但是将其与其他行进行比较。我一直在寻找一种一致的方式来做到这一点。
      猜你喜欢
      • 1970-01-01
      • 2018-12-14
      • 2017-01-19
      • 1970-01-01
      • 1970-01-01
      • 2018-12-08
      • 1970-01-01
      • 2019-03-20
      • 2014-07-09
      相关资源
      最近更新 更多