简体   繁体   中英

Converting months and years to date in java

If in the program someone gives me the number of days(ab="days") I need to set the variable 'days' as the same number(value in 'val'), if some one gives me the months(ab="months") then I need to convert(value in 'val') it into days, if someone gives me years(ab="years") then I need to convert(value in 'val') it into days. ie if the user specifies the type of values(ie whether it is month or year or date) in variable 'ab' and the number (of days/months/years) in variable 'val', I need to get number of days in the variable 'days'.

For example ab="years" and val = 3 then days is 1095(approximate).

What I tried is as below. Is it the right approach for the above problem? Thanks in advance.

public class conversionofdate {
        public static void main(String args[]) {
            String ab = "days";
            int val = 0, days, month = 0, years = 0;
            switch (ab) {
                case "days":
                    days = val;
                    break;
                case "months":
                    days = val * 30;
                    break;

                case "years":
                    days = val * 12 * 30;
                    break;
                default:
                    System.out.println("Incorrect value");
            }
        }
    }

So you want to keep track of time in java. You should start by reading this:

https://docs.oracle.com/javase/tutorial/datetime/iso/index.html

And you should be aware that this is not a simple problem. Date and Time have subtle nuances that lead to mind bending bugs as explored here:

Why is subtracting these two times (in 1927) giving a strange result?

and here

Java string to date conversion

Also, be aware that not everyone on the planet uses the gregorian calendar most of us english speakers use. In addition to months having different numbers of days and leap years there are also fun arcane issues like leap seconds. There are also systems that measure time in milliseconds since jan 1 1970 that don't give a fig about corrections. It's great glorious fun trying to sort out where the error is when these different systems get turned into strings in documents that get read into computers that use a different system.

In short the answer to your question is beyond the scope of what can be done justice to in a stack overflow answer. Suffice it to say, just stay away from java.util.Date and use java.util.Calendar . Date will break your heart .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM