64

I'm trying to parse a string to a date field in an android application but I can't seem to get it correct. Here is the string I'm trying to convert to a date "03/26/2012 11:49:00 AM". The function I'm using is:

private Date ConvertToDate(String dateString){
    SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa");
    Date convertedDate = new Date();
    try {
        convertedDate = dateFormat.parse(dateString);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return convertedDate;
}

But I keep getting 3/1/112 11:49AM as the result.

Edit: everyone was right. it was converting correctly but i was using the Date.getYear(), getMonth() and all those which i was using incorrectly.

7
  • 3
    Where are you seeing "3/1/112 11:49AM"? The returned value is a Date, not a string, so you must be doing something to see it as a string result... Commented Mar 30, 2012 at 14:38
  • 1
    I see Mon Mar 26 11:49:00 IST 2012 as output. Commented Mar 30, 2012 at 14:40
  • try to set the parsing to lenient using dateFormat.setLenient(true), and then check the results of your parsing Commented Mar 30, 2012 at 14:40
  • Maybe your avd is not properly configured. Sometimes it happens to me. Commented Mar 30, 2012 at 14:45
  • 1
    I strongly recomment that you use java.time, the modern Java date and time API for all date and time work. See the good answer by Arvind Kumar Avinash. With java.time you will never be able to make the errors you made with the old-fashioned and poorly designed Date class. Commented Aug 10 at 14:23

7 Answers 7

120

You are wrong in the way you display the data I guess, because for me:

    String dateString = "03/26/2012 11:49:00 AM";
    SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa");
    Date convertedDate = new Date();
    try {
        convertedDate = dateFormat.parse(dateString);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println(convertedDate);

Prints:

Mon Mar 26 11:49:00 EEST 2012
Sign up to request clarification or add additional context in comments.

1 Comment

everyone was right. it was converting correctly but i was using the Date.getYear(), getMonth() and all those which i was using incorrectly. Thanks for all you help.
18

it went OK when i used Locale.US parametre in SimpleDateFormat

String dateString = "15 May 2013 17:38:34 +0300";
System.out.println(dateString);

SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy HH:mm:ss Z", Locale.US);
DateFormat targetFormat = new SimpleDateFormat("dd MMM yyyy HH:mm", Locale.getDefault());
String formattedDate = null;
Date convertedDate = new Date();
try {
     convertedDate = dateFormat.parse(dateString);
System.out.println(dateString);
formattedDate = targetFormat.format(convertedDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
 System.out.println(convertedDate);

1 Comment

It’s not answering the question. Also today no one should use SimpleDateFormat, DateFormat and Date since they were troublesome and for that reason supplaned by java.time, the modern Java date and time API, in Java 8, 6 months after this answer was posted
2
String str_date="13-09-2011";
DateFormat formatter ; 
Date date ; 
formatter = new SimpleDateFormat("dd-MM-yyyy");
date = (Date)formatter.parse(str_date); 
System.out.println("Today is " +date.getTime());

Try this

1 Comment

It’s not answering the question at all. Also today no one should use DateFormat, Date and SimpleDateFormat since they were troublesome and for that reason supplaned by java.time, the modern Java date and time API, in Java 8.
2

This code will help you to make a result like FEB 17 20:49 .

    String myTimestamp="2014/02/17 20:49";

    SimpleDateFormat form = new SimpleDateFormat("yyyy/MM/dd HH:mm");
    Date date = null;
    Date time = null;
    try 
    {
        date = form.parse(myTimestamp);
        time = new Date(myTimestamp);
        SimpleDateFormat postFormater = new SimpleDateFormat("MMM dd");
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        String newDateStr = postFormater.format(date).toUpperCase();
        String newTimeStr = sdf.format(time);
        System.out.println("Date  : "+newDateStr);
        System.out.println("Time  : "+newTimeStr);
    }
    catch (Exception e) 
    {
        e.printStackTrace();
    }

Result :

Date : FEB 17

Time : 20:49

Comments

2

The accepted answer, will work only by chance when the system's Locale is an English locale. It will fail if the system's Locale is non-English. It is because a date-time formatting/parsing type is locale-sensitive, and since 03/26/2012 11:49:00 AM is in English, an English locale should be specified with the formatting/parsing type. Check Always specify a Locale with a date-time formatter for custom formats to learn more about it.

The answer by mDonmez has used an English Locale but the format does not match the input string.

java.time

The modern java.time date-time API, introduced with Java 8 in March 2014, supplanted the error-prone legacy java.util date-time API. It is highly recommended to use java.time API for any new code.

Solution using java.time API

Your input does not have a time zone. Use a DateTimeFormatter with the required format to parse the input into a LocalDateTime.

Demo:

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    private static final DateTimeFormatter PARSER =
            DateTimeFormatter.ofPattern("MM/dd/uuuu hh:mm:ss a", Locale.ENGLISH);

    public static void main(String[] args) {
        String strDateTime = "03/26/2012 11:49:00 AM";
        LocalDateTime ldt = LocalDateTime.parse(strDateTime, PARSER);
        System.out.println(ldt);
    }
}

Output:

2012-03-26T11:49

Online Demo

Formatted output:

enter image description here

I have added the following section, thanks to Anonymous.

DateTimeFormatter FORMATTER =
        DateTimeFormatter.ofPattern("M/d/uuuu hh:mma", Locale.ENGLISH);
System.out.println(ldt.format(FORMATTER));

Output:

3/26/2012 11:49AM

Online Demo

Learn more about the modern Date-Time API from Trail: Date Time.

5 Comments

inaccurate: 1) system's locale is only relevant if the default Locale is not changed (in Java); 2) accepted answer will still work with some non-English locales (e.g. French, German, Italian, Portuguese, ...); ( caution: code in this answer would not work for Locale.UK despite being English - UK requires lowercase "am" AFAIK )
user85421, Your comment does not make any sense to me. The code in this answer is guaranteed to work. This is the whole idea of using a Locale with a DateTimeFormatter explicitly.
I have tested with en-GB and with da-DK as default locales. It works fine. You may argue that the first sentence or the first paragraph of the answer does not give the whole and accurate truth. I still find the explanation most helpful.
user85421, I have no idea what you want to prove. Your wrong code uses DateTimeFormatter.ofPattern("MM/dd/uuuu hh:mm:ss a", Locale.UK) while my correct code uses DateTimeFormatter.ofPattern("MM/dd/uuuu hh:mm:ss a", Locale.ENGLISH). Why would anyone use Locale.UK for the given string? The DateTimeFormatter instance must have the pattern and Locale conforming to the input string.
0
GregorianCalendar date;

CharSequence dateForMart = android.text.format.DateFormat.format("yyyy-MM-dd", date);

Toast.makeText(LogmeanActivity.this,dateForMart,Toast.LENGTH_LONG).show();

Comments

-1
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateInString = "07/06/2013";

try {

    Date date = formatter.parse(dateInString);
    System.out.println(date);
    System.out.println(formatter.format(date));

} catch (ParseException e) {
    e.printStackTrace();
}

Output:

2014/08/06 16:06:54
2014/08/06 16:06:54

1 Comment

1) the question is about parsing a string with date and time; 2) the output is very strange: parsing 07/06/2013 but output is 2014/08/06 ... 3) the last output does not match the formatter -- maybe it was different 10 years ago, but I would expect a time of 0:00:00 since no time was parsed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.