convert string to german date java - java

my problem is the following. I would like to have the german date for the string "11.11.2012".
I tried this piece of code:
String date = "11.11.2012";
SimpleDateFormat sdtF = new SimpleDateFormat("dd.mm.yyyy",Locale.GERMANY);
Date dareFormatiert = sdtF.parse(date);
System.out.println(dareFormatiert);
But it gives me the wrong format. "Wed Jan 11 00:11:00 CET 2012", instead of "11.11.2012".
Thank you, any help is appreciated.

You have to use M in you pattern, because M is the month and m is the minute!
String date = "11.11.2012";
SimpleDateFormat sdtF = new SimpleDateFormat("dd.MM.yyyy",Locale.GERMANY);
^^^^
Date dareFormatiert = sdtF.parse(date);
System.out.println(dareFormatiert);
For more information see the documentation of SimpleDateFormat

but i still have the same output: Sun Nov 11 00:00:00 CET 2012
Try to understand the thing when you use
SimpleDateDFormat#parse() - It parses text from a string to produce a Date.
and Date object in java always contains date along the time.
Javadoc says Date() - Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.
and FYI Sun Nov 11 00:00:00 CET 2012 is equal to 11.11.2012
Edit: try this
public static Date convertUtilDateToSqlDate(java.util.Date date){
if(date != null && !(date.equals(""))) {
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
return sqlDate;
}
return null;
}
pass the util date you got above and this method shall return the sql format date then store the sqlformat date in mysql column-field of type Date

Related

Converting date to GMT

I want to convert a date to GMT.
I get a date in BST, I want to convert it to GMT without time zone conversion.
Example:
**If the BST date is: Wed June 26 13:30:13 BST 2019
I want to convert it to Wed 26 Jun 2019 13:30:13 GMT**
I want to ignore the timezone info and return the same date as GMT.
For this I am trying
private SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
private SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
private SimpleDateFormat dateFormatGmtText = new SimpleDateFormat("EEE dd MMM yyyy HH:mm:ss 'GMT'");
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
String textDate = dateFormatLocal.format(date);
//Date is Wed June 26 13:30:13 BST 2019
private Date toGMTDate(final Date date) {
String textDate = dateFormatLocal.format(date);
try {
String[] dateParts = textDate.split("\\+");
textDate = dateParts[0] + "+0000";
return dateFormatGmt.parse(textDate);
} catch (ParseException e) {
return null;
}
}
private String toGMT(final Date date) {
return dateFormatGmtText.format(toGMTDate(date));
}
When I call toGMT it returns Wed 26 Jun 2019 14:30:13 GMT
I am not sure why it is so?
What is wrong here?
java.time
You said you can’t use the modern date and time API, but for other readers I should like to present that option first. SimpleDateFormat and Date are poorly designed and long outdated, the former in particular notoriously troublesome, so I recommend avoiding them.
I am assuming that BST is for British Summer Time (other interpretations exist). And I am assuming that you cannot avoid getting an old-fashioned Date object.
private static DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("EEE dd MMM yyyy HH:mm:ss z", Locale.UK);
private static ZoneId britain = ZoneId.of("Europe/London");
private static ZoneId gmt = ZoneId.of("Etc/GMT");
private static String toGMT(final Date date) {
ZonedDateTime britishTime = date.toInstant().atZone(britain);
ZonedDateTime gmtTime = britishTime.withZoneSameLocal(gmt);
return gmtTime.format(formatter);
}
Try it out with your Date of Wed Jun 26 13:30:13 BST 2019:
String textDate = dateFormatLocal.format(date);
System.out.println(textDate);
System.out.println(toGMT(date));
Output is:
2019-06-26T13:30:13+0100
Wed 26 Jun 2019 13:30:13 GMT
Whenever you get an old-fashioned Date, the first thing to do is to convert it to Instant. Then do any further conversions from there. The key to changing time zone and keeping the date and time of day (hour-minute-second of day) is the withZoneSameLocal method of the ZonedDateTime class.
I recommend specifying locale for the formatter.
I am not sure why it is so? What is wrong here?
A Date hasn’t got, as in cannot have a time zone. It’s a point in time, nothing more. YourtoGMTDate method returns a point in time that is an hour later: The time you gave it was 13:30:13+0100, and it returned 13:30:13+0000, which is the same point in time as 14:30:13+0100. Next you formatted this point in time using a formatter that used your default time zone, Europe/London, and therefore produced 14:30:13, but at the same time printed GMT in the string — the result you reported.
…the new time library, but for some reasons I can't use them.
If you really have got an evil boss that either forces you to use Java 1.4 or 1.5 and/or forbids the use external dependencies, the pretty simple hack is:
private String toGMT(final Date date) {
return dateFormatGmtText.format(date);
}
The cheating is: Your dateFormatGmtText uses your default time zone, Europe/London, but lies and prints GMT in the formatted string. This gives the same output as above — the output you asked for. Compared to your code I am just leaving out the date conversion.
Link: Oracle tutorial: Date Time explaining how to use java.time.

comparison of SimpleDateFormat

i have a date was hard coded as a string but now i'm to fetch the expired date from the database and compare with it the current time. Here is a sample of the hard coded date stored in the database:2015-02-24T13:00:00.000Z and now i have to compare this date to the current time and to check if it the date is expired. How can this be resolved by comparing the current date and time in exactly this format?
You can do it in following simple way
SimpleDateFormat input = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:sss");
SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d = input.parse("2015-02-24T13:00:00.000Z");
System.out.println(d);
String formattedTime = output.format(d);
System.out.println(formattedTime);
The SysOut will be the like this
Tue Feb 24 13:00:00 IST 2015
2015-02-24 13:00:00
For Comparison with current date do it in following way
SimpleDateFormat input = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:sss");
Date dbDate = input.parse("2015-02-24T13:00:00.000Z");
System.out.println("dbDate"+dbDate);
System.out.println(dbDate.compareTo(new Date()));
sysout will be like this
dbDateTue Feb 24 13:00:00 IST 2015
-1
here output will be -1 means dbDate is older than current date
if output is 1 than dbDate is newer than current date.

Same date different long time

i've a object Date as for example this date "Fri Aug 01 00:00:00 CDT 2014" that through this validation:
Date fechaInicio = filtros.containsKey("dateFechaInicio") ? Fecha.getMinDate(Fecha.getFecha(filtros.get("dateFechaInicio").toString())) : Fecha.getMinDate(null);
Where map filtros contains the key "dateFechaFinal" it will to method Fecha.getMaxDate(Date date) that does
public static Date getMinDate(Date fecha) {
Calendar fechaMin = Calendar.getInstance();
fechaMin.setTime(fecha != null ? fecha : new Date());
fechaMin.set(fechaMin.get(Calendar.YEAR),
fechaMin.get(Calendar.MONTH),
fecha != null ? fechaMin.get(Calendar.DAY_OF_MONTH) : fechaMin.getActualMinimum(Calendar.DAY_OF_MONTH),
fechaMin.getActualMinimum(Calendar.HOUR_OF_DAY),
fechaMin.getActualMinimum(Calendar.MINUTE),
fechaMin.getActualMinimum(Calendar.SECOND));
return fechaMin.getTime();
}
And return a new Date, if this method receives a date return this Long time 1406869200806 , but if receives a date equal to null the method takes the first day from month for example "Fri Aug 01 00:00:00 CDT 2014" but now return this Long time 1406869200000..
"filtros obtained a String that method getFecha() convert to new Date"
Why happen it?
You're only setting values down to the second, so the millisecond part is left at whatever it was from new Date(). Your description isn't entirely clear, but I suspect you just want:
fechaMin.set(Calendar.MILLISECOND, 0);
Alternatively, use a better API, such as Joda Time or the java.time API in Java 8.

Parse a string to date in specific format

I have a TimeStamp '2013-06-24 10:46:11.0' and I need to cut off the .0 part, so what I did was to use the SimpleDateFormat to parse it to String and back then parse it to date, the first conversion was fine but the second (string to date) throws a java date time.
public void convert(Object object) {
Date date;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
date = object().getDate();
String formated = format.format(date);
try {
date = format.parse(formated);
} catch (ParseException ex) {
Logger.getLogger(DlgConsultaFactura.class.getName()).log(Level.SEVERE, null, ex);
}
}
What I expect is a date like this 2013-06-24 10:46:11, but what I got is this date Mon Jun 24 10:46:11 CDT 2013
Any help will be appreciated. Thanks.
Mon Jun 24 10:46:11 CDT 2013 and 2013-06-24 10:46:11 is actually same value. Mon Jun 24 10:46:11 CDT 2013 is as per your default locale.
You're getting confused between date's internal representation and its display format.
To print in 2013-06-24 10:46:11 you can use same SimpleDateFormat object again.
You can use DateFormat#format(Date) to print the date or return the String representation in your desired format i.e. "yyyy-MM-dd HH:mm:ss". Something like this:
String myDt = format.format(date);
// 2013-06-24 10:46:11
Not the best way but a quick and easy one if you want just the string representation of the date ...
formated = formated.substring(0, formated.length()-2);
:)
DateFormat i.e. SimpleDateFormat just formats the date as per your need.
Parse returns the Date representation of the String (or timestamp in your case) passed in.
Format returns the String representation of the Date object passed in.
In both the cases , you see the same date just the representation is different.

Difference between two dates with different timezones

I'm trying to obtain the difference between two dates but i'm stuck at converting a string into a date.
My code is:
//create a date send it to the database as string
Date currentDate = new Date(); // date looks like: Sat Sep 01 10:20:14 EEST 2012
SaveToDB(currentDate.ToString());
At some point i;m trying to retrieve the date from the database:
String dateStringFromDb = GetDateFromDB(); //Sat Sep 01 10:20:14 EEST 2012
Date currentDate = new Date();
//now i'm trying to covnert the dateStringFromDb into a Date, this throws an exception
Date dbDate = DateFormat.getInstance().parse(dateStringFromDb); //this throws exception
long difference = currentDate.getTime() - dbDate.getTime(); // does this give me the correct difference in GMT even if timezones for the two dates are different?
Can you please point me to the correct solution?
Unfortunately the date from the database is retrieved as a String and i can't change that to another type. So i need to convert that string into Date().
EDIT:
Exception is :
java.text.ParseException: Format.parseObject(String) failed
at java.text.Format.parseObject(Unknown Source)
at main.Program.main(Program.java:20)
I would suggest using Joda Time API for your data and time related operation in Java. Handling timezone and all related conversion nuances are pretty easy using this API.
You should specify a DateFormat to match the string format being received
Eg.
SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");
String reformattedStr = myFormat.format(fromUser.parse(inputString));
Once you have the both the dates in required format, then apply the date arithmetic operations
Other Format Specifiers for DateString can be found in
http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

Categories

Resources