Get & set date / time and format

First tried this method:

Calendar c = Calendar.getInstance();
int year, month, day, hour, minute;
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH) + 1;	//months are 0-11 !!
day = c.get(Calendar.DAY_OF_MONTH);
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
String date1 = day + "/" + month + "/" + year;
String time1 = hour + ":" + minute;

But found this method to be simpler to get a formatted date and time:

        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm dd-MM-yyyy");
        Calendar cal = Calendar.getInstance();
        Date now = cal.getTime(); // set the current datetime in a Date-object
        // SimpleDateFormat.format( Date date ) returns a formatted string
        // with the predefined format
        String mTimeString = sdf.format( now );

To create date from string.

DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date rateDate = (Date)formatter.parse(myString);

 

This entry was posted in Android. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *