开发者

Calculate date from a number

I need a method which would give me the number of hours and minutes from any random number.For example if the random number is 500 i would like to have information as 5 hrs and 0 minutes.Another example is 2359 is 23 hrs 59 minutes.The random number is entered by the user and i am only concerned with the hours and minutes(not seconds).I need not even worry about rounding off of minutes .So i wrote this method ,which to me is not efficient.Can any one suggest a be开发者_如何学Gotter way of doing it ?or is this good enough?

 private void calculateDateTime(int someNumber){

    if(someNumber<=0){
        return;
    }

  String number = Integer.toString(someNumber);
  String hrs ="";
  String mins ="00";
  if(number.length()>4){
      hrs =number.substring(0, 2);
      mins = number.substring(2,4);
  }
  else{
      float f =((float)someNumber)/100;
      String s = Float.toString(f);
      String [] splitArray = s.split("\\.");
      if(splitArray.length>1) {
      hrs = splitArray[0];
      mins = splitArray[1];
      }
  }
 int hr = Integer.valueOf(hrs);
 int min = Integer.valueOf(mins);
 if(hr>=24||min>=60){
     return;
 }

Thats how i am getting the hr and mins respectively.Suggest me a better approach if you have one.

Thanks


Pad the input string with zeros until length is 4 and then spilt the string in the middle?


Maybe:

int hours = someNumber / 100;
int minutes = someNumber % 100;

if(hours >= 24 || minutes >= 60) {
    //Do whatever
}


If you want your values to be repeatable, I would use the passed in value as the seed into a Random generator.

Random r = new Random(someNumber);
int hr = r.nextInt(24);
int min = r.nextInt(60);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜