【问题标题】:How to count months and years in one variable?如何在一个变量中计算月份和年份?
【发布时间】:2013-11-19 18:55:44
【问题描述】:

所以我目前正在开发一个模拟器,将年份和月份存储为两个单独的变量,如下所示:

static double currentYear = 1;
static double currentMonth = 1;

它会像这样更新:

if(currentMonth == 12){
currentYear++;
currentMonth = 1;
}else{
currentMonth++;
}

我对 DecimalFormat 类非常陌生,但我知道可以创建一个读取年份:####,月份:## 的输出,但我遇到的问题是它必须显然每十二个月添加一年而不是十个月,就像正常数字一样。 有没有更简单的计算方法或者我的方法最简单?

【问题讨论】:

  • 为什么你把它标记为sql? static double 不在 sql 中!!!
  • 我不知道它推荐了 sql,我真的不知道还有什么可以标记它,所以我很抱歉。
  • 这对于这里的许多人来说真的很惊讶,因为您不知道您面临问题或编码的语言!
  • 为什么不使用Date 类型并且每次只添加一个月?

标签: static decimalformat


【解决方案1】:

创建一个自定义类型来表示您的持续时间(以年和月为单位)。像这样的:

class YearMonthDuration
{
  private int durationInMonths ;

  public int Years  { get { return durationInMonths / 12 ; } }
  public int Months { get { return durationInMonths % 12 ; } }

  public YearMonthDuration( int years , int months )
  {
    this.durationInMonths = years * 12 + months ;
    return ;
  }

  public static explicit operator int( YearMonthDuration instance )
  {
    return instance.Years*100 + instance.Months ;
  }

  public override string ToString()
  {
    return string.Format("Years={0}/Months={1}" , Years , Months ) ;
  }

  public YearMonthDuration AddYears( int years )
  {
    durationInMonths += years*12 ;
    return this ;
  }
  public YearMonthDuration AddMonths( int months )
  {
    durationInMonths += months ;
    return this ;
  }

}

【讨论】:

    【解决方案2】:

    你可以随时使用时空交易。浪费计算机周期来存储更多数据。 以相同的方式将时间存储在许多计算机上 - UNIX Timestamp 计算自纪元以来的秒数,然后您从中计算日期,以类似的方式您可以存储您的月份和年份。只需使用一个整数来存储总月数,然后在输出时使用

    "Year: " + floor(totalMonths/12) + " Month: " + ((totalMonths % 12) + 1);
    

    其中 % 是取模运算符(即可以是 mod 或类似的东西,具体取决于您选择的语言),而 floor 只是一个向下舍入到较小整数的函数。

    顺便说一句,格式化是您可以在 Internet 上查找的另一个问题,有很多相关指南。

    【讨论】:

      猜你喜欢
      • 2015-06-20
      • 2019-09-08
      • 1970-01-01
      • 1970-01-01
      • 2021-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-06
      相关资源
      最近更新 更多