String to Date not formatted correctly - java

I am trying to do a simple String to Date conversion in Java. I am skimming the date off some logs and need to convert it to a date to do some processing. A date coming through will look like this:
2012-09-07 19:53:33
In my code when I try to convert this into a Date object I get a completely different date. My code looks like this:
String taskStart = "2012-09-07 19:53:33";
String dateFormat = "yyyy-MM-dd hh:MM:ss";
SimpleDateFormat dateFormat=new SimpleDateFormat(format);
Date taskStartDate = dateFormat.parse(taskStart);
The output I get is this:
Sat May 07 19:00:27 PDT 2016
How can I just simply convert my original date to the correct format??

You've specified MM (month in year) twice. The m's for "minute" must be lowercase.
If you're taking 24-hour based times, you need to specify HH in order to capture hours that are specified in the range of 0-23, as opposed to hh which expects AM/PM hours (hours in the range of 1-12 with an AM/PM specifier as part of the time string)
Finally, your example code doesn't define the format variable that you're passing into the constructor for your SimpleDateFormat object. In fact, you're using the variable name dateFormat twice and not defining the format variable at all - at least not according to the code that you included in the question.
So, your proper format string, I believe, should be...
"yyyy-MM-dd HH:mm:ss"
...and the full, proper code example would be:
String taskStart = "2012-09-07 19:53:33";
String format = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat dateFormat=new SimpleDateFormat(format);
Date taskStartDate = dateFormat.parse(taskStart);

According to the documentation for SimpleDateFormat you should use an upper case "H" for hours of the format 0-23. Also, minutes are represented by a lowercase "m".
String dateFormat = "yyyy-MM-dd HH:mm:ss";

I think you should convert again the date output to String format using date formatter.format function:
Date formatter=new SimpleDateFormatter("yy-MM-dd HH mm ss")
String s=formatter.format(taskStartDate)

Try changing your dateFormat definition to this:
String dateFormat = "yyyy-MM-dd HH:mm:ss";
Note that the in your time, HH should be capitalized for 0-23 and mm should be lowercase for minute.

"yyyy-MM-dd hh:MM:ss";
MM and mm are for Month and Minute respectively.....
So it should be...
"yyyy-MM-dd hh:mm:ss";

Related

Java String to Date object of the format “MM/dd/yyyy HH:mm:ss a”

I need to convert a String containing a date into a date object.
The String will be in the format "yyyy-mm-dd HH:mm:ss" and I want the "MM/dd/yyyy HH:mm:ss a " format as result.
String dateString = "2018-03-20 09:31:31";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss a",
Locale.ENGLISH);
LocalDate date = LocalDate.parse(dateString , formatter);
The code above is throwing an exception.
You have to use two Formatter, one to covert String to LocalDateTime and the other to format this date as you want :
From String to LocalDateTime :
String dateString = "2018-03-20 09:31:31";
LocalDateTime date = LocalDateTime.parse(
dateString,
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH)
);
Now From LocalDateTime to String :
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
"MM/dd/yyyy HH:mm:ss a", Locale.ENGLISH
);
String newDate = date.format(formatter);
System.out.println(newDate);// 03/20/2018 09:31:31 AM
Note : You have to use LocalDateTime instead of just LocalDate, your format contain both date and time, not just date, else you will get an error :
java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: HourOfDay
That's a common error, based on the misconception that dates have formats - but they actually don't.
Date/time objects have only values, and those values - usually numerical - represent the concept of a date (a specific point in the calendar) and a time (a specific moment of the day).
If you have a String, then you don't actually have a date. You have a text (a sequence of characters) that represents a date. Note that all of the strings below are different (they have a different sequence of characters), but all represent the same date (the same values, the same point in the calendar):
2018-03-20 09:31:31
03/20/2018 9:31:31 AM (using USA's format: month/day/year)
Tuesday, March 20th 2018, 09:31:31 am
and many others...
What you want to do is to get one format (one String, one text representing a date) and transform it to another format (anoter String, another different sequence of characters that represents the same date).
In Java (and in many other languages - if not all - btw) you must do it in 2 steps:
convert the String to a date/time object (convert the text to the numerical values) - that's what the parse method does
convert the date/time object to another format (convert the numerical values to another text)
That said, when you call the parse method, you're trying to transform a String (a text, a sequence of characters) into a date/time object. This means that the DateTimeFormatter must have a pattern that matches the input.
The input is 2018-03-20 09:31:31, which is year-month-day hour:minute:second. And the formatter you used to parse it has the pattern MM/dd/yyyy HH:mm:ss a (month/day/year hour:minute:second am/pm).
You used the output pattern (the one that should be used in step 2) to parse the input. That's why you've got an exception: the formatter tried to parse a month with 2 digits followed by a / when the input actually contains a year with 4 digits followed by a -.
You must use a different DateTimeFormatter for each step, using the correct pattern for each case. YCF_L's answer has the code that does the job, I'd just like to add one little detail. The formatter used for the output (step 2) is:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
"MM/dd/yyyy HH:mm:ss a", Locale.ENGLISH
);
Note that HH is used for the hours. Take a look at the javadoc and you'll see that uppercase HH represents the hour-of-day fields (values from 0 to 23 - so 1 AM is printed as 01 and 1 PM is printed as 13).
But you're also printing the AM/PM field (the a in the pattern), so maybe what you need is actually the lowercase hh, which is the clock-hour-of-am-pm (values from 1 to 12) or even KK (hour-of-am-pm (values from 0 to 11)).
String dateString = "2018-03-20 09:31:31";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date = formatter.parse(dateInString);
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
String reportDate = df.format(date );
} catch (ParseException e) {
e.printStackTrace();
}
You need to do a 2 steps conversion:
from your String date time in the wrong format to a (tempoary) LocalDateTime object.
if you still want to only extract the date (Year-Month-day) do a LocalDateTime.toLocalDate()
From this LocalDateTime object into the your String object in the right format
String dateString = "2018-03-20 09:31:31";
DateTimeFormatter formatterForWrongFormat = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE)
.appendLiteral(" ")
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.toFormatter();
//1- from String(wrong format) into datetime object
LocalDateTime dateTime = LocalDateTime.parse(dateString , formatterForWrongFormat);
// 1.1 extract date object (Optional)
LocalDate myDate = dateTime.toLocalDate();
// 2- now from your LocalDateTime to the String in the RIGHT format
DateTimeFormatter formatterForRightFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss a",
Locale.ENGLISH);
System.out.println("right format: "+dateTime.format(formatterForRightFormat));
you can test this code here
You can use the SimpleDateFormatter which is easier to implement and permit you to change the format of your date easily.
More here : What are the date formats available in SimpleDateFormat class?
Hope this will help you !

how to get time stamp for the example: 2016-08-29T09:15:17Z?

I have tried to get the date format 2016-08-29T09:15:17Z but not able to get the trailing Z at the end.
I also checked the date time documentation at official website but could not find a similar pattern. So far the date format I have created is as follows:
yyyy-MM-dd'T'HH:mm:ss.SSSZ
So far the code I have written is:
public static void main(String args[]) throws ParseException{
Date nDate=new Date();
//SimpleDateFormat format=new SimpleDateFormat("ddMMYYYYHHMMSS");
String date=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").format(nDate);
System.out.println(date);
}
The T is just a literal to separate the date from the time, and the Z means "zero hour offset" also known as "Zulu time" (UTC). If your strings always have a "Z" you can use -
TimeZone timeZone = TimeZone.getTimeZone("UTC"); // optional
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // Quoted "Z" to indicate UTC, no timezone offset
dateFormat.setTimeZone(timeZone); // optional
String date = dateFormat .format(new Date()); // date will have the required format
System.out.println(date);
Z is a constant value like T in your string, so you have to put single quotes arround it:
String date=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").format(nDate);
If you use Z without single quotes DateFormat expect the timezone value
Oracle Documentation describe that z and Z both are use for time zone.
So if you don't want special meaning of Z then you need to write like :
yyyy-MM-dd'T'HH:mm:ss'Z'
I am adding another way to do it, using the new java.time API introduced from JDK 8 onwards.
LocalDateTime nDate=LocalDateTime.now();
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE)
.appendLiteral('T')
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.appendLiteral('Z')
.toFormatter();
String date = formatter.format(nDate);
System.out.println(date);

I want to convert date format

I am using Java and I want to change my date format which will ignore initial zeros in date and time. Something like "2/2/2015 1:30 PM" instead of "02/02/2015 1:30PM"
you can use a SimpleDateFormat
SimpleDateFormat formatter = new SimpleDateFormat("d/MM/yyyy hh:mma");
String date = formatter.format(today);
see this link for the char codes:
http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

How to convert into Timestamp format in Java?

I am getting the date time in "1/23/2013 6:57:17 AM" format and need to convert it into "2012-01-01T12:00:00" format. I could have solved the issue by using string functions and separating the date and time and dealing with them individually. But the problem is compunded by the fact that the date format is M/D/YYYY and even time has only h:mm:ss which means i cannot assume the number of characters before each delimiter.
I hope someone has dealt with something like this before. Thanks.
No, String functions are not the way to go.
I'd recommend using two DateFormat instances: one for the source format and another for the target format.
DateFormat source = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
source.setLenient(false);
DateFormat target = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
target.setLenient(false);
String dateAsString = "1/23/2013 12:00:00 AM";
Date d = source.parse(dateAsString);
System.out.println(target.format(d));

Java - Date constructor accepts a Date String, But deprecated. Tried alternatives, but no luck

String temp_date="07/28/2011 11:06:37 AM";
Date date = new Date(temp_date); //Depricated
SimpleDateFormat sdf = new SimpleDateFormat("MMM-dd-yyyy hh:mm:ss");
String comp_date= sdf.format(date);
System.out.println(comp_date);
This works, But If I use something like this
String temp_date="07/28/2011 11:06:37 AM";
try{
SimpleDateFormat sdf = new SimpleDateFormat("MMM-dd-yyyy hh:mm:ss");
Date comp_date= sdf.parse(temp_date);
System.out.println(comp_date);
}catch(Exception e){
System.out.println(e);
}
This exception is thrown:
java.text.ParseException: Unparseable date: "07/28/2011 11:06:37 AM"
Your parsing pattern is wrong. It does not match the date string representation. The MMM denotes a 3-letter localized month abbreviation, while you have 2-digit month number in your actual date, you need MM. You've also slashes / as date/month/year separator and not -. For the AM/PM marker you also need an a afterwards so that the right hh can be parsed.
This should work:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
For an explanation of those patterns, read the SimpleDateFormat javadoc.
I believe that your concrete functional requirement is to convert the given date string as specified by the pattern MM/dd/yyyy hh:mm:ss a into another date string format, as specified by the pattern MMM-dd-yyyy hh:mm:ss. In that case, you should then have two SimpleDateFormat instances, one which parses the string in the given pattern to a Date and another which formats the parsed Date to the given pattern. This should do what you want:
String inputDate = "07/28/2011 11:06:37 AM";
Date date = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a").parse(inputDate);
String outputDate = new SimpleDateFormat("MMM-dd-yyyy HH:mm:ss").format(date);
System.out.println(outputDate); // Jul-28-2011 11:06:37
Note that I changed hh in output to be HH because it would otherwise end up in 1-12 hour representation without an AM/PM marker. The HH represents it as 0-23 hour.
The format you gave the SimpleDateFormat uses - between the month, date, and year. Your string uses slashes.
At first look, it looks as if your format string is wrong.
MMM -- You specified this for the month, but you aren't passing a 3 char month.
Try MM and see if that helps.
Take a look at this for some additional date format information:
http://www.java2s.com/Tutorial/Java/0040__Data-Type/SimpleDateFormat.htm

Categories