Java - SimpleDateFormat parse from String issue - java

I'm trying to parse the following string to a Date object:
String str = "04/15/2014 10:30:24"
I'm using SimpleDateFormat :
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
java.util.Date orderDate = sdf.parse(str);
java.sql.Date orderSqlDate = new java.sql.Date(orderDate.getTime());
but orderSqlDate always returned: 04/15/2014 00:00:00
how to use SimpleDateFormat in java exactly?

The java.sql.Date javadoc states
To conform with the definition of SQL DATE, the millisecond values
wrapped by a java.sql.Date instance must be 'normalized' by setting
the hours, minutes, seconds, and milliseconds to zero in the
particular time zone with which the instance is associated.
If you're going to use java.sql.Date, there's no way around this.

You are also doing correct.
But to get the result in the format you want, you need to use .format("/your format/") method after parsing the string.
String date = "15/12/2014 10:42:24";
SimpleDateFormat dateParser = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date parseDate = dateParser.parse(date);
formatter.format(parseDate) // this will change format of date as you want.

I don't think the way you parse is wrong. Are you sure you print orderDate right ?
The following code demonstrates both parsing and formatting (printing).
public static void main(String[] args) {
String format = "MM/dd/yyyy HH:mm:ss";
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date orderDate = new SimpleDateFormat(format).parse("04/15/2014 10:30:24");
System.out.println(sdf.format(orderDate));
} catch (Exception e) {
e.printStackTrace();
}
}

Provide Locale in the SimpleDateFormat constructor, otherwise parsing might be dependant on your local settings:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.ROOT);

Related

Convert custom date string(with am/pm) to UTC Date Time using java

I just need sample code block or suggestion to convert the following date string to utc time in format yyyy-MM-dd HH:mm:ss?
sample date string:11/23/2017 09:44am
there are similar questions like this but my test data is with am/pm.So pls dont consider this as duplicate
You could use the Java 8 time package:
String input = "11/23/2017 09:44am";
String format = "MM/dd/yyyy hh:mma";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
LocalDateTime date = LocalDateTime.parse(input, formatter);
System.out.printf("%s%n", date);
But the problem is: this throws a DateTimeParseException, because of the lowercase 'am'.
I looked up in the docs, but I couldn't see a standard way to parse lowercase 'am' or 'pm' as as meridiem designator1. You'll end up manually replacing them:
input = input.replace("AM", "am").replace("PM","pm");
As mentioned by #OleVV in the comments, you can use a DateTimeFormatterBuilder and specify that the parsing should be case-insensitive:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern(format)
.toFormatter();
Then you can use this formatter as argument to the LocalDateTime.parse method.
Another answer of the aforementioned post provides a solution where you can override the AM/PM symbols with the lowercase variants.
1 Interestingly, the SimpleDateFormat does support the parsing of lowercase am/pm.
The sample code below should do the conversion correctly.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateConversion {
public static void main(String[] argv) {
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mma");
SimpleDateFormat OutputFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String sampleDateString = "11/23/2017 09:44am";
try {
Date convertDate = formatter.parse(sampleDateString);
System.out.println(OutputFormatter.format(convertDate));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
This is to declare the date string to be parsed.
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mma");
and the output date as well
SimpleDateFormat OutputFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
At first you need to create a SimpleDateFormat with the proper pattern. This class helps you to parse your string to java.util.Date (more info here):
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy hh:mma");
If your original string-date is in a special timezone then you need to instruct the parser to use this timezone:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy hh:mma", Locale.ENGLISH);
Then you need to parse the string to date:
Date d = sdf.parse("11/23/2017 09:44am");
Finnaly you have to convert the timezoned date to UTC.
Please find bellow the full code snippet:
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy hh:mma", Locale.ENGLISH);
Date d = sdf.parse("11/23/2017 09:44am");
System.out.println(toUtcZonedDateTime(d));
}
public static ZonedDateTime toUtcZonedDateTime(final Date date) {
if (date == null) {
return null;
}
final ZoneId utcZone = ZoneOffset.UTC;
return ZonedDateTime.ofInstant(date.toInstant(), utcZone);
}
Output:
2017-11-23T08:44Z
SimpleDateFormat's javadoc lists all the options, including "a" for am/pm marker.
In you case, you need:
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ssa")

i want to convert date fromat: "mm/dd/yyyy hh:mm" to "yyyy-mm-dd hh:mm:ss"

Response from jsp is coming in this format: "mm/dd/yyyy hh:mm", and I want to convert to db format "yyyy-mm-dd hh:mm:ss".
I tried this code :
public java.sql.Date getdateFormat(String datestring) throws ParseException {
String datestr = "";
try {
java.util.Date date = new SimpleDateFormat("mm/dd/yyyy hh:mm a",
Locale.ENGLISH).parse(datestring);
atestr = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(date);
} catch (Exception e) {
e.printStackTrace();
}
return getDateFromString(datestr);
}
public java.sql.Date getDateFromString(String string) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
java.util.Date finalDate = null;
try {
finalDate = sdf.parse(string);
} catch (Exception e) {
e.printStackTrace();
}
return new java.sql.Date(finalDate.getTime());
}
A common mistake in using SimpleDateFormat is skip the documentation and assume that is knows when mm means months and when mm mean minutes. It doesn't. mm only means minutes. If you want months use MM Also only use a if you expect AM/PM and only use hh for 12 hour clocks. I would expect your format should read
MM/dd/yyyy HH:mm
and your output
yyyy-MM-dd HH:mm:ss
BTW You shouldn't need to convert to a String to use JDBC. Using a Date is faster and less error prone.
If all you want is the Date then you do not need to do
atestr=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(date);
simply return the date as this stage.
A date does not have any formatting, it is basically a number.
I would basically do it like this
String dateInString = "20140611";
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Date toDate = sdf.parse(dateInString);
sdf = new SimpleDateFormat("yyyy-MM-dd");
String tmpStr = String.format(sdf.format(toDate));
System.out.println(tmpStr);
We can get the date in the following way
DateFormat dfm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date parseDate = dfm.parse(datestring);
Now the parseDate is in the format "yyyy-MM-dd HH:mm:ss"

convert a date object to Oracle timestamp type string

I want to convert a date object, ex: new Date(), to a string which has a format like Oracle's time stamp type, ex: 21-OCT-13 11.08.13.858000000 AM. I know I could just get each piece of information in the date object like day, month, year, hour, minute, ... to form the Oracle format string but I really want to know is there a utility to do that instead?
Using SimpleDateFormat#format() you would print a Date as
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy hh.mm.ss.SSSSSSSSS a");
System.out.println(sdf.format(new Date()).toUpperCase());
Output :
21-OCT-13 10.01.38.000000614 AM
See JavaDocs for Date and Time patterns.
Try taking a look at SimpleDateFormats - That would be your best bet and easiest way of doing it.
Eg:
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm:ss"); //Hours:Minutes:Seconds
String strDate = dateFormat.format(date);
Use SimpleDateFormat.
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("your_format_here"); // dd/MM/yy h:mm:ss a
String formattedDate = sdf.format(date);
System.out.println(formattedDate);

How to format a date String into desirable Date format

I was trying to format a string into date.
For this I have written a code:-
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
System.out.println(sdf.format( cal.getTime() ));
This is fine..
But now I want to convert a string into a date formatted like above..
For example
String dt="2010-10-22";
And the output should be like this:-
2010-10-22T00:00:00
How do I do this?
String dt = "2010-10-22";
SimpleDateFormat sdfIn = new SimpleDateFormat("yyyy-MM-dd");
ParsePosition ps = new ParsePosition(0)
Date date = sdfIn.parse(dt, pos)
SimpleDateFormat sdfOut = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
System.out.println(sdfOut.format( date ));
This should do it for you, remember to wrap it in a try-catch block just in case.
DateFormat dt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
try
{
Date today = dt.parse("2010-10-22T00:00:00");
System.out.println("Your Date = " + dt.format(today));
} catch (ParseException e)
{
//This parse operation may not be successful, in which case you should handle the ParseException that gets thrown.
//Black Magic Goes Here
}
If your input is going to be ISO, you could also look at using the Joda Time API, like so:
LocalDateTime localDateTime = new LocalDateTime("2010-10-22");
System.out.println("Formatted time: " + localDateTime.toString());
The same class you use for output formatting of dates can also be used to parse dates on input.
SimpleDateFormat reference
To use your example, to parse the sample date:
String dt = "2010-10-22";
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(dateFormatter.parse(dt));
The fields that are not specified (ie. hour, minutes, etc) will be 0. So your same code can be used to format the date on output.
Date Format Example
Containing the Conversion of String Date object from one format to another

DateTime formatter

I am developing an application and I am stuck in converting string like 01/01/2037 01:00:00 AM
to Date
I used
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh.mm.ss.S aa")
Date d = dateFormat.parse(dateString);
but I get an error, any help will be appreciated.
you are converting this 01/01/2037 01:00:00 AM
therefore use
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss aa")
(more info in [documentation])1
then
Date date = dateFormat.parse("01/01/2037 01:00:00 AM");
keep in mind you have to wrap a try-catch around the parse method.
The problem is that the format you declared is nothing like the String you are trying to parse:
your String uses / to separate day, month, year while in your formatter you use -
your string separates hours with a dot, while in the formatter you use :
you do not have milliseconds in your string while you declared them in the formatter.
The following code should work:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh.mm.ss.S aa");
try {
Date date = dateFormat.parse("01-01-2037 01.00.00.000 AM");
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}

Categories

Resources