Issue with Java Date format - java

Inside my application I allow my users to enter some dates, which I should save in DB. Now since some of my application users are located in different locations worldwide and each have their own date/time format, I thought of accepting any date format from them, then change those formats to a fixed format which I can then save in DB.
Yet my problem now is that I getting an error when trying to change date fromat from that entered by the user to my application format, below is the code I am currently working with
Entity field:
#Temporal(TemporalType.TIMESTAMP)
#Column(name="DDATE", nullable=false, unique=false)
private Date dDate;
Controller code that save in DB:
Date rDate, dDate;
String Date1 = request.getParameter("Date1");
String Date2 = request.getParameter("Date2");
//Here the date get display for example as 01/29/2014 (i.e. MM/DD/YYYY)
System.out.println("Date1:: "+ Date1);
System.out.println("Date2:: "+ Date2);
SimpleDateFormat parseRDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat parseDDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
//#########Crashes in the next two lines#########...
rDate = (Date)parseRDate.parse(Date1);
dDate = (Date)parseDDate.parse(Date2);
} catch (ParseException e) {
e.printStackTrace();
}
So can someone please suggest how I can format any date entered by my users to the application static date format?
Thanks

My suggestion is to use http://en.wikipedia.org/wiki/ISO_8601 as universal date for everyone.
If anyone can enter any string, you'll never know if 08/12/75 is December 8th or August 12th
From the wikipedia:
Date and time (current at page generation)
expressed according to ISO 8601:
Date: 2014-01-11
Combined date and time in UTC: 2014-01-11T12:21:05+00:00
2014-01-11T12:21Z
Week: 2014-W02
Date with week number: 2014-W02-6
Ordinal date: 2014-011

Related

How to Set Date to JdateChooser in java?

enter image description here
I used java Jcalender_1.4.jar
I have date like this,
String date = "13 Oct 2016";
i want this date set to JdateChooser text box,
by using this command JdateChooser.setDate();
how to covert string in to date format ?
You can do it using this easily by SimpleDateFormat command
String date = "13 Oct 2016";
java.util.Date date2 = new SimpleDateFormat("yyyy-MM-dd").parse(date);
JdateChooser.setDate(date2);
and also you can use any date format.
Calendar ca = new GregorianCalendar();
String day = ca.get(Calendar.DAY_OF_MONTH) + "";
String month = ca.get(Calendar.MONTH) + 1 + "";
String year = ca.get(Calendar.YEAR) + "";
if (day.length() == 1) {
day = "0" + day;
}
if (month.length() == 1) {
month = "0" + month;
}
String dd = year + "-" + month + "-" + day;
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(dd);
jDateChooser1.setDate(date);
try this set date form computer date
The following was first written as an answer to this duplicate question. I thought it would be better to have it here so we have all the answers in one place.
The following should work overall, only the details depend on the format of the dates in the JTable (from the other question). I have assumed that from the JTable you get a string like 03/07/2018 (I am told that this format would be commonplace in Portugal). In this case the following formatter will be fine for parsing it. If the string is in a different format, the formatter will have to be different too.
DateTimeFormatter dtfFormatador = DateTimeFormatter
.ofLocalizedDate(FormatStyle.MEDIUM)
.withLocale(Locale.forLanguageTag("pt-PT"));
LocalDate data = LocalDate.parse(getData, dtfFormatador);
Instant instante = data.atStartOfDay(ZoneId.systemDefault()).toInstant();
Date dateAntiquado = Date.from(instante);
jdcSeletorDeDatas.setDate(dateAntiquado);
Unfortunately JDateChooser.setDate() requires an old-fashoined Date object, while we’d have preferred to avoid that outdated class. I am using a DateTimeFormatter for parsing the string from the JTable into a LocalDate and converting it to Date. LocalDate is the class from java.time, the modern Java date and time API, that we should use for a date without time of day.
Edit: harsha, your string was
String date = "13 Oct 2016";
To parse a string in this format, use the following formatter:
DateTimeFormatter dateFormatter= DateTimeFormatter
.ofLocalizedDate(FormatStyle.MEDIUM)
.withLocale(Locale.US);
Otherwise use the code above, where jdcSeletorDeDatas is the JDateChooser.
Link: Oracle tutorial: Date Time explaining how to use java.time.
try {
String date = "13 Oct 2016";
Date date2 = new SimpleDateFormat("dd MMM yyyy").parse(date);
jDateChooser2.setDate(date2);
} catch (Exception e) {
System.out.println(e);
}
Right Click on JDateChooser
Go to Properties
Change dateFormatString as "dd MMM yyyy"
Try to cast the value to the Date type. This Worked for me:
int SelectRow = jTable1.getSelectedRow();
jDateChooser1.setDate((Date) jTable1.getModel().getValueAt(SelectRow, 2));

Oracle Date Format change to yyyy-MM-dd hh:mm:ss

I have date saletime as 2/25/14 22:06 I want to store it in oracle table in the yyyy-MM-dd hh:mm:ss. So I wrote following java code
Date saleTime = sale.getSaleTime();
logger.info("DateTime is "+saleTime);
SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date saleTimeNorm = formatter.parse(formatter.format(saleTime));
logger.info("DateTime after Formating "+saleTimeNorm);
Timestamp oracleDate = new Timestamp(saleTimeNorm.getTime());
logger.info("New Format Inserting :"+oracleDate);
sale.setSaleTime(oracleDate);
But this seems to be giving :0014-02-25 22:06:00.0
Any suggestions ?
Your getSaleTime() method somehow regards "14" as a four-digit year, and returns the year 14.
After you have executed getSaleTime(), you already have a Date variable; there is no need (and no use) in converting it to a different output format and re-parsing the result. The Date you get from the calls to format() and parse() will be the same one you started with.
You can create your Timestamp using getTime() on the result of the call to getSaleTime(). That will be correct once you change getSaleTime() so that it returns the date in the correct year.
Something must be wrong in your sale.getSaleTime() method. Because the following code working as needed.
Date saleTime = Calendar.getInstance().getTime();
SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date saleTimeNorm = formatter.parse(formatter.format(saleTime));
Timestamp oracleDate = new Timestamp(saleTimeNorm.getTime());
System.out.println(oracleDate);
//2014-05-13 03:58:53.0

How to convert "MM-dd-yyyy hh:mm" String date format to GMT format?

My Date format is like as "MM-dd-yyyy hh:mm" its not current date ,I have to send this date
to server but before send it need to change this date to GMT format but when I change by following code:
private String[] DateConvertor(String datevalue)
{
String date_value[] = null;
String strGMTFormat = null;
SimpleDateFormat objFormat,objFormat1;
Calendar objCalendar;
Date objdate1,objdate2;
if(!datevalue.equals(""))
{
try
{
//Specify your format
objFormat1 = new SimpleDateFormat("MM-dd-yyyy,HH:mm");
objFormat1.setTimeZone(Calendar.getInstance().getTimeZone());
objFormat = new SimpleDateFormat("MM-dd-yyyy,HH:mm");
objFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
//Convert into GMT format
//objFormat.setTimeZone(TimeZone.getDefault());//);
objdate1=objFormat1.parse(datevalue);
//
//objdate2=objFormat.parse(datevalue);
//objFormat.setCalendar(objCalendar);
strGMTFormat = objFormat.format(objdate1.getTime());
//strGMTFormat = objFormat.format(objdate1.getTime());
//strGMTFormat=objdate1.toString();
if(strGMTFormat!=null && !strGMTFormat.equals(""))
date_value = strGMTFormat.split(",");
}
catch (Exception e)
{
e.printStackTrace();
e.toString();
}
finally
{
objFormat = null;
objCalendar = null;
}
}
return date_value;
}
its not change in required format ,I have tried by above code first try to get current timeZone and after that try change string date into that timezone after that convert GMT.
anyone guide me.
thanks in advance.
Try the below code. The first sysout prints the date object which picks up default OS timezone i.e. IST in my case. The second sysout prints the date in the required format after converting the date to GMT timezone.
If you know the timezone of your date string then set that in the formatter. I assumed you need the same date format in the GMT timezone.
SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy,HH:mm");
Date date = format.parse("01-23-2012,09:40");
System.out.println(date);
format.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(format.format(date));
you need to use TimeZone's getRawOffset() method:
Date localDate = Calendar.getInstance().getTime();
TimeZone tz = TimeZone.getDefault();
Date gmtDate = new Date(date.getTime() - tz.getRawOffset());
it
returns the amount of time in milliseconds to add to UTC to get standard time in this time zone. Because this value is not affected by daylight saving time, it is called raw offset.
If you want to consider DST as well (you might want this ;-) )
if (tz.inDaylightTime(ret)) {
Date dstDate = new Date(gmtDate.getTime() - tz.getDSTSavings());
if (tz.inDaylightTime(dstDate) {
gmtDate = dstDate;
}
}
The last check is needed if you are right on the edge of a summer time change and would, for instance, go back into standard time by the conversion.
Hope that helps,
-Hannes

Retreving date from Hibernate TImestamp

I have a field with temporal type as Timestamp to save both date and time to the database.
#Temporal(TemporalType.TIMESTAMP)
#Column(name="date", nullable=false)
private Date date;
But when displaying the value to the user, I just want to show date part and truncate time part. I tried this but I get ParseException probably because of the Nanosecond part of the Hibernate Timestamp.
SimplDateFormat sd = new SimpleDateFormat("MM/dd/yyyy");
return sd.parse(date.toString());
So how do I retrieve just date from Hibernate Timestamp? Thanks
Just format the date object. The toString method isn't guaranteed to give you a string in a format that can then be parsed.
String dateStr = sd.format(date);
That will give you a date string in MM/dd/yyyy format that you can then convert back into a Date.
Date fancyNancy = sd.parse(dateStr);
* EDIT *
Run this code and verify it prints out the day, month and year with no time.
try {
Date d = new Date();
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
System.out.println("Original Date: " + d);
System.out.println("Formatted Date: " + df.parse(df.format(d)));
} catch (Exception e) {
e.printStackTrace();
}

change string to date as per the required date Format

I have to get a Date in type Date, not in String.
I have this code:
DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
Date date1 = new Date();
String date = (formatter.format(date1));
// At this point I get the date in correct format i.e 05/24/11
Date todaysDate = (Date)formatter.parse(date);
// But after this I get the date in format : Tue May 24 00:00:00 EDT 2011
// whereas I Want to get the date like above i.e 05/24/11
// And in type Date, not in type String
If anyone could help, thanks
The Date object just represents a point in time and has no notion of a format (or time zone). If you print out a Date object it first converts it to a String using the default formatting of EEE MMM dd HH:mm:ss zzz yyyy. If you want a specific formatting when you print it or otherwise represent it as a String, you'll need to use a formatter just like you already have.
In other words, you want Date.toString() to return the same as DateFormat.format()? You could just do exactly that:
public class MyDate extends Date {
DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
public String toString() {
return this.formatter.format(this);
}
}
But do you really want to mix up presentation (date format) with your data?
There is no problem here, you have a Date representing and can save it into the DB as it is now. If you print it to the console it gets formatted according the default rules, this is why you think it is different from what you need, but it has actually already the right value.
So just go ahead and put it into your DB.
Chances are that you DB will hold on getting a Timestamp, in this case you can create one:
Date d = ...
java.sql.Timestamp ts = new java.sql.Timestamp(d.getTime());
and save this one.

Categories

Resources