Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calendar return wrong current date android

Why does this code return 0001-02-05?

public static String getNowDate() throws ParseException
{        
    return Myformat(toFormattedDateString(Calendar.getInstance()));
}

I changed the code to:

public static String getNowDate() throws ParseException
{        
    Calendar temp=Calendar.getInstance();
    return temp.YEAR+"-"+temp.MONTH+"-"+temp.DAY_OF_MONTH;
}

And now it returns 1-2-5.

Please, help me get the actual date. all i need is the Sdk date.

like image 665
Eduardoxvii Avatar asked Oct 25 '12 18:10

Eduardoxvii


3 Answers

Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH are int constants (just look up in the API doc)...

So, as @Alex posted, to create a formatted String out of a Calendar instance, you should use SimpleDateFormat.

If however you need the numeric representations of specific fields, use the get(int) function:

int year = temp.get(Calendar.YEAR);
int month = temp.get(Calendar.MONTH);
int dayOfMonth = temp.get(Calendar.DAY_OF_MONTH);

WARNING! Month starts from 0!!! I've made some mistakes because of this!

like image 153
ppeterka Avatar answered Sep 28 '22 00:09

ppeterka


Use SimpleDateFormat

new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime());

You are using constants to be used with the Calendar.get() method.

like image 45
Alex Avatar answered Sep 27 '22 22:09

Alex


Why not use SimpleDateFormat?

public static String getNowDate() {
  return new SimpleDateFormat("yyyy-MM-dd").format(new Date());
}
like image 43
GriffeyDog Avatar answered Sep 28 '22 00:09

GriffeyDog