DateTime formatter - java

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();
}

Related

Java Date TIME Format AM/PM Configuration

I am facing problems some while formatting the date:
Date : 11/06/2020 04:14:20
Date Format:dd/MM/yyyy hh:mm:ss a
Exception:
java.text.ParseException: Unparseable date: "11/06/2020 04:14:20"
Following is the code
Blockquote
public String getFormatDate(String inputDate) {
String strDate = "";
try {
DateFormat outputFormat = new SimpleDateFormat("MMMM dd, yyyy hh:mm:ss a");
DateFormat inputFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
Date date1 = inputFormat.parse(inputDate);
strDate = outputFormat.format(date1);
}catch( Exception exe) {
exe.printStackTrace();
logger.error( "[ERROR] getFormatDate:. ", exe );
}
return strDate;
}
Blockquote
Any help would be greatly appeciated.
You can check this code you have to pass the am/pm part too with the date string value as your format is expecting that.
//String date = "11/06/2020 04:14:20";
String date = "11/06/2020 04:14:20 am";
DateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
https://ideone.com/3nibwJ
Use proper date-time objects for your dates and times
For the vast majority of purposes you should not keep your date and time in a string and should not convert your date and time from a string in one format to a string in another format. Keep your date and time in a ZonedDateTime or LocalDateTime object.
When you are required to accept string input, parse that input into a date-time object immediately. I am using and recommending java.time, the modern Java date and time API:
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu HH:mm:ss");
String input = "11/06/2020 04:14:20";
LocalDateTime dateTime = LocalDateTime.parse(input, inputFormatter);
System.out.println(dateTime);
Output so far is:
2020-06-11T04:14:20
Since there is no AM or PM in your string, I have assumed that 04:14:20 was the time of day from 00:00:00 through 23:59:59. If you intended otherwise, you need to explain how.
Only when you need to give string output, format your date and time back into a string of appropriate format:
DateTimeFormatter outputFormatter = DateTimeFormatter
.ofPattern("MMMM dd, yyyy hh:mm:ss a", Locale.ENGLISH);
String output = dateTime.format(outputFormatter);
System.out.println(output);
June 11, 2020 04:14:20 AM
Do provide a locale for the formatter so Java knows which language to use for the month name and the AM/PM indicator.
What went wrong in your code?
Your string has no AM nor PM: 11/06/2020 04:14:20. Yet your format pattern string requires an AM/PM marker in the end. This is what format pattern letter a signifies. So your string wasn’t in the format that you required. This was the reason for the exception that you observed.
Link
Oracle tutorial: Date Time explaining how to use java.time.
Thanks All for your help:
I have changed the source date "11/06/2020 04:14:20" to "06/11/2020 04:14:20 PM", and then after perform follwoing steps, its working for me:
Blockquote
DateFormat inputFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
inputFormat.setTimeZone( TimeZone.getTimeZone("UTC") );
Date dDate = inputFormat.parse( srcDate );
String strDeDate = formatDateToString( dDate, "dd/MM/yyyy hh:mm:ss a", "IST" );
public String formatDateToString(Date date, String format,String timeZone) {
if (date == null) return null;
SimpleDateFormat sdf = new SimpleDateFormat(format);
if (timeZone == null || "".equalsIgnoreCase(timeZone.trim())) {
timeZone = Calendar.getInstance().getTimeZone().getID();
}
sdf.setTimeZone(TimeZone.getTimeZone(timeZone));
return sdf.format(date);
}
Blockquote

Solving Parse Date Exception

i have a string "12/3/2014 12:00:00 AM" and i want to cast this string in date which have format like this "yyyy-MM-dd HH:mm:ss"
#DatabaseField(columnName="out_date",dataType=DataType.DATE_STRING,format="yyyy-MM-dd HH:mm:ss")
private Date out_date;
above is the object to get value from date string
SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
outlet.setOut_date(formater.parse(json.getString("outletDate")));
after i using like the error occur java.text.ParseException: Unparseable date: ... (at offset 2) how to solve that problem thank in advance
Based on this answer, you need something like this. First convert your string in its present format to a date object, then reformat the date object.
String date = "12/3/2014 12:00:00 AM";
SimpleDateFormat sdf = new SimpleDateFormat("mm/dd/yyyy HH:MM:SS a");
Date testDate = null;
try {
testDate = sdf.parse(date);
}catch(Exception ex){
ex.printStackTrace();
}
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String newFormat = formatter.format(testDate);
System.out.println(".....Date..."+newFormat);
Conversion steps :
Create date object from your date format.
Target date format provide to SimpleDateFormat class constructor.
Parse date using SimpleDateFormat.
The code provided convert yyyy-MM-dd HH:mm:ss to dd/mm/yyyy HH:mm:ss format.
try {
SimpleDateFormat sdf1 = new SimpleDateFormat("dd/mm/yyyy HH:MM:SS a");
Date date = sdf1.parse("12/3/2014 12:00:00 AM");
String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
System.out.println(format);
}catch(Exception e){
e.printStackTrace();
}
Error : java.text.ParseException: Unparseable date: ... (at offset 2) indicates that you are using wrong date format to parse your sting.

Android SimpleDateFormat always returns wrong week day

I have the following code:
String s = "08-12-2014 05:00:00"
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
SimpleDateFormat outputFormat = new SimpleDateFormat("EEEE, HH:mm a");
Date oneWayTripDate = null;
try {
oneWayTripDate = inputFormat.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
String datetime = outputFormat.format(oneWayTripDate);
but for some weird reason it always returns the wrong day of the week. what am i doing wrong?
The input SimpleDateFormat pattern is wrong. Given the date 08-12-2014 05:00:00 with the year part at the end, and assuming 08 is the month, the format should be:
SimpleDateFormat inputFormat = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss", Locale.ENGLISH);
See the Javadoc of SimpleDateFormat for how to define date patterns.

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"

Java - SimpleDateFormat parse from String issue

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);

Categories

Resources