user3997016
user3997016

Reputation:

How to convert string to date format and return type must be date

I have written the following code :

Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);

String newDAte = String.valueOf(day) + "-" + String.valueOf(month + 1) + "-" + String.valueOf(year);

SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");

try {

    Date d = dateFormat.parse(newDAte);
    System.out.println("DATE" + d);
    System.out.println("Formated" + dateFormat.format(d));

    d = dateFormat.parse(String.valueOf(d));

    Toast.makeText(MainActivity.this, String.valueOf(d), Toast.LENGTH_SHORT).show();

} catch (Exception e) {

    System.out.println("Excep" + e);
}

When i toast it it shows me date like wednesday spetember 10 2016 ...

Now when i convert it to string then its shows perfect output : 26-10-2016

String sdate = String.valueOf(dateFormat.format(d))

But it is return as string and i want as a date type like:

Date newD = dateFormat.format(d);

But it is not working.

I want output like 26-10-2016 but it must return/store into Date variable

How can i return it with date type ?

Upvotes: 0

Views: 856

Answers (2)

Anil
Anil

Reputation: 1614

Here you can find two function which can convert millies to Date and Date to Millies

Milles to Date format.

private String convetTimeStamp(String time) {
    Calendar cal = Calendar.getInstance();
    long Time = Long.parseLong(time);
    cal.setTimeInMillis(Time * 1000);
    String date = DateFormat.format("dd-MM-yyyy  hh:mm a", cal).toString();

    return date;
}

just remove hh:mm a if u dont want time

Date to Millies

private long dateToMillies(String time)
{
    Date date = null;

    try {
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
        formatter.setLenient(false);
        date = formatter.parse(time);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return (date.getTime()/1000);
}

Upvotes: 0

Magesh Pandian
Magesh Pandian

Reputation: 9369

See below. This is work for me.

 String dateString = "26-10-2016";
        convertDateFormat(dateString);

 private Date convertDateFormat(String data) {
    try {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
        Date date = simpleDateFormat.parse(data);
        Log.d(TAG," test==>"+date);
        return date;
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return null;
}

Output: test==>test==>Wed Oct 26 00:00:00 GMT+05:30 2016 (Date format)

Upvotes: 1

Related Questions