2011-02-14 70 views
0

我想用户得到六位数吐了3个部分的(日,月,年)将6位整数分成3部分?

例子:

int date=111213; 
day =11; 
month =12; 
year =13; 

我想我已经把它转换到字符串然后通过使用substring()我可以做到这一点。

任何简单的想法??

+2

如何将日期中最早2010年1月的用原来的整数来表示? – 2011-02-14 14:44:18

+0

还是2001年1月的第一个? – 2011-02-14 16:04:06

回答

6

如何:

// Assuming a more sensible format, where the logically most significant part 
// is the most significant part of the number too. That would allow sorting by 
// integer value to be equivalent to sorting chronologically. 
int day = date % 100; 
int month = (date/100) % 100; 
int year = date/10000; 

// Assuming the format from the question (not sensible IMO) 
int year = date % 100; 
int month = (date/100) % 100; 
int day = date/10000; 

(?你来存储这样的数据开始与伊克)

+0

像往常一样比光更快 - 只是听着你在这个开发者的生活播客;-)谈话你看起来你的网络是好的;-) – 2011-02-14 14:43:53

1

存储一个日期作为这样一个整数不是很理想,但如果你必须这样做 - 而且你确信,这一数目将始终使用指定的格式 - 那么你可以很容易地提取日,月和年:

int day = date/10000; 
int month = (date/100) % 100; 
int year = date % 100; 
1

你可以用模块化算术做到这一点:

int day = date/10000; 
int month = (date/100) % 100; 
int year = date % 100; 
0

这里是一个没有优化Java中的解决方案:

final int value = 111213; 
    int day; 
    int month; 
    int year; 

    day = value/10000; 
    month = (value - (day * 10000))/100; 
    year = (value - (day * 10000)) - month * 100;