2011-02-14 78 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;