Javed Akram
Javed Akram

Reputation: 15344

spliting 6 digit int into 3 parts?

I want to get a six digit number by user and spit it into 3 parts as(day, month, year)

Example:

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

I think I have to convert it into string then by using substring() I can do this.

Any easy Idea ??

Upvotes: 0

Views: 551

Answers (4)

Jon Skeet
Jon Skeet

Reputation: 1501033

How about:

// 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;

(Do you have to store your data like this to start with? Ick.)

Upvotes: 6

DwB
DwB

Reputation: 38300

Here is the solution in Java with no optimization:

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

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

Upvotes: 0

Gabe
Gabe

Reputation: 86718

You can do this with modular arithmetic:

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

Upvotes: 1

LukeH
LukeH

Reputation: 269428

Storing a date as an integer like this isn't ideal, but if you must do it -- and you're sure that the number will always use the specified format -- then you can easily extract the day, month and year:

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

Upvotes: 1

Related Questions