Can't get date from DateChooserCombo - java

I'm trying to get the date from DateChooserCombo as follows
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD");
String date = sdf.format(dateChooser.getDate());
But the method getDate() gives me error (illegal forward reference). I have also tried with getSelectedDate() but it's the same. What can I do?
Anyway I'm using Apache Netbeans 12.1 and the date picker should be this one:
https://github.com/vadimig/jdatechooser
Thanks.

I downloaded the JDateChooser code from the link you provided in your question. There is no getDate() method in class datechooser.beans.DateChooserCombo. There is a getSelectedDate() method which returns an instance of class java.util.Calendar.
Also, according to the documentation for class java.text.SimpleDateFormat, the pattern YYYY-MM-DD is a valid pattern but I don't think it's the pattern that you want. D means day in year which means that 27th February is the 58th day of the year. You probably want d. Similarly, Y means Week year whereas you probably wanted y.
So, in order to get a string representation of the date that the user selected from the DateChooserCombo, you probably want the following code.
DateChooserCombo dcc = new DateChooserCombo(); // or however you create and configure it
Calendar cal = dcc.getSelectedDate();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date = sdf.format(cal.getTime());
By the way, it appears that JDateChooser development stopped seven years ago. Perhaps consider using JavaFX which has a DatePicker component which works with Java's date-time API.

Related

App crashes when I use SimpleDateFormat class with "YYYY"

I am using SimpleDateFormat class to get current year like this
SimpleDateFormat currentYear = new SimpleDateFormat("YYYY");
Date thisYear = new Date();
String stringThisYear = currentYear .format(thisYear );
It is working fine in here(India) ,but it crashed when it run on Malaysia by other people.After lot of debugging and searching ,i found that it is happening due to no mention of locale.So I changed my code to this
SimpleDateFormat currentDate = new SimpleDateFormat("YYYY", Locale.ENGLISH);
Still it is crashing, so I use calendar instance to get current year like this
int thisYear=Calendar.getInstance().get(Calendar.YEAR);
But i want to know what is issue with simpleDateFormat as most of my code is already has simpleDateFormat class.So I want to know the reason for crash,if anyone has solution,Please help me.Thank you
It's because you must use "yyyy" instead of "YYYY"
On old versions of Android, using "YYYY" makes your app to crash. Nothing to do with the country/Locale
"Y" stands for week year and not year, as specified in the Javadoc
EDIT 2
More information here
yyyy is the pattern string to identify the year in the
SimpleDateFormat class.
Java 7 introduced YYYY as a new date pattern to identify the date week
year.
An average year is exactly 52.1775 weeks long, which means that
eventually a year might have either 52 or 53 weeks considering
indivisible weeks.
Using YYYY unintendedly while formatting a date can cause severe
issues in your Java application.
As mentioned by #OleV.V., the format Y is only supported on Android API 24+. Using any versions below API 24 makes the app to crash.
Try to use default locale for the device like this
SimpleDateFormat currentDate = new SimpleDateFormat("YYYY", Locale.getDefault());
I am facing the same issue using this it's working fine.
SimpleDateFormat formatter = new SimpleDateFormat("YYYY",Locale.US);

Format a String to a Fixed Date at UTC+0 in Java

I want to convert a String date - 2017-01-01 to java.util.Date with UTC+0. So, what I am expecting is.
"2017-01-01" -> 2017-01-01T00:00:00 UTC+0100
Here is how I am trying to do, but as my default Timezone is UTC+1, I am getting that 1 hour added to the Date.
Date d = Date.from(Instant.parse("2017-01-01T00:00:00Z"));
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss 'UTC'ZZZZZ");
String output = sf.format(d);
System.out.println(output);
Here is the output:
2017-01-01T01:00:00 UTC+0100
Can somebody help?
Your code is mixing oldfashioned and modern classes. Date and SimpleDateFormat are long outdated. Instant is modern (from 2014). I recommend you stick to the modern ones unless you are working with an old API that requires and/or gives you an instance of an oldfashioned class. So the answer is
String output = LocalDate.parse("2017-01-01")
.atStartOfDay(ZoneOffset.ofHours(1))
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss 'UTC'XX"));
The result is the one you asked for
2017-01-01T00:00:00 UTC+0100
The code is not really shorter than yours, but once you get used to the fluent style you will find it clearer and more natural. The room for confusion and errors is considerably reduced.
If you want the start of day in whatever time zone the user is in, just fill in ZoneId.systemDefault() instead of ZoneOffset.ofHours(1).
LocalDate parses your date string — "2017-01-01" — without an explicit format. The string conforms to ISO 8601, and the modern classes use this standard as their default for parsing and also for their toString().
You can set the timezone first and then format it.
sf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = sf.parse(d);
And now format as per your requirements:
String output = sf.format(date);
System.out.println(output);
I wonder please try this also:
Date date = new Date();
TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
Calendar cal = Calendar.getInstance(TimeZone.getDefault());
date = cal.getTime();

Java Types: What is the format for representing a variable of type `Date`? `Time`?

I have a varaibles:
Date date;
Time time;
and methods:
MyDateMethod(Date date){
//do stuff
}
MyTimeMethod(Time time){
//do stuff
}
I tried using MyDateMethod() with the following call:
MyDateMethod(1995-03-7);
I get an error saying I've supplied it with type int when it expected type Time.
I also tried using MyTimeMethod() with the following call:
MyTimeMethod(03:04:55);
I get an error saying Type mismatch: Cannot convert type int to boolean.
What is the format to put in a variable of these different types? Date is obviously not xxxx-xx-xx and Time is obviously not xx:xx:xx.
There are a few options,
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Date d = sdf.parse("1995-03-07");
System.out.println(d);
} catch (ParseException e) {
e.printStackTrace();
}
Output is
Tue Mar 07 00:00:00 EST 1995
Or, you could use
// -1 because January is 0... I didn't design it!
Calendar c = new GregorianCalendar(1995, 3 - 1, 7);
System.out.println(c.getTime());
with the same output as before.
SimpleDateFormat is what You need. It's need to be initialized by format of date.
Use it like this:
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy/MM/dd HH:mm:ss", Locale.getDefault());
and then:
Date date = (Date) dateFormat.parse("2014/04/02 22:22:22");
Take a look at DateFormat and particularly SimpleDateFormat.
Your example would be coded like this, using SimpleDateFormat:
Date date = new SimpleDateFormat("yyyy-MM-dd").parse("1995-03-07")
(I'm assuming you have months before days here, you will need to interchange the MM and dd if not).
Java does not support Date literals. You need to use a constructor or a static factory method to obtain an instance of this class.
1995-03-07 returns 1985 because you have three int literals here and the hyphens are interpreted as subtraction operators.
Take a look at the documentation for the Date class and the DateFormat class
Here's a way you could represent these values:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = dateFormat.parse("1995-03-07");
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
Date time = timeFormat.parse("03:46:16");
You can use the same format objects to perform the reverse of this conversion. Please mind that these Date instances represent a specific moment in time, down to millisecond level. Internally, this is represented as the number of milliseconds since January 1, 1970, 00:00:00 GMT
This API is hardly the prettiest one in Java and by looking at the docs you can see how many changes it has undergone. Just look at the number of deprecated methods.
I recommend taking a look at the Joda-Time library instead.
Alternatively, if using Java 8 is an option for you, you can try the brand new API that comes with it
The answer by Tom is correct. No date-time literals inJava.
And as he stated, the old bundled java.util.Date and .Calendar classes are notoriously troublesome. Avoid them. Use either the Joda-Time library or the new java.time package in Java 8.
Joda-Time
In Joda-Time:
If you want only a date without time and time zone, use the LocalDate class.
Similarly to use only time while ignoring time zone and date, use the LocalTime class.
But most often you'll probably want to use the DateTime class which tracks date, time, and time zone all in one object.
A Date-Time Is Not Text
A DateTime object does not contain text. No String. If you need a string representation, use a formatter object to generate one. Search StackOverflow for many examples.
Built into Joda-Time are formatters for the sensible and increasingly common ISO 8601 standard. For example, the toString implementation on the DateTime class produces a String like this…
2014-04-01T20:17:35-08:00

util.date to sql.date giving the wrong date

String d = request.getParameter("date");
SimpleDateFormat dateFormat = new SimpleDateFormat("mm-dd-yyyy");
java.util.Date utilDate = dateFormat.parse(d);
java.sql.Date date = new java.sql.Date(utilDate.getTime());
The above code is to get a date from a form and get it into sql.date format to use in a prepared statement, however the date being produced is wrong, 03-14-2012 is being converted to 2012-01-14 +00:00:00
Am i doing this the right way?
Your DateFormat is incorrect mm are minutes, MM are months.
Regards
As burna has said, your date formatting is incorrect. For a full list of formats, refer to: http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
As you can see, months are defined by MM. For a Month-Day-Year date, you should be looking at the format: "MM-dd-yyyy" Hope that helps.
The problem is not with the call to the java.sql.Date constructor. If you print out utilDate you will see that the value is already wrong at that point.
The issue is your SimpleDateFormat string - it should be "MM-dd-yyyy", that is, with the M's capitalized. See the javadoc for all the conversion codes.

I want to get a formatted Date in Java

I want to get a new Date object with a SimpleDateFormat applied to it. I would like to do something like:
SimpleDateFormat myFormat = new SimpleDateFormat("dd MMM yyyy kkmm");
Date today = new Date();
today = myFormat.format(today);
I can't do this, because today is a Date, and format returns a String. I also have tried:
Date today;
SimpleDateFormat myFormat = new SimpleDateFormat("dd MMM yyyy kkmm");
try{
today = myFormat.parse((new Date()).toString());
}catch(Exception e){
}
This isn't a good solution, because when I try to use today elsewhere Java complains that today may not have been instantiated. What is a good way to change the format of a Date object (while still keeping it a Date object, and not turning it to a string)?
You are looking at Format and Date wrongly.
Date does not contain format. Date is just a class containing date info like date, month, hours, sec etc.
SimpleDateFormat is the one which tells you the string representation of Date. But there is no date associated with it.
So the idea is when you have to display date or have to store date in some string representation, you will use SimpleDateFormat and pass it the date you want string representation for.
One benefit of doing this way is that, I can use same Date object and can show two different string representations (using two different instances of SimpleDateFormat). And also viceversa, having defined one SimpleDateFormat instance, I can format multiple dates.
Edit:
Now if you want to strip some info from the date. Use
Calendar rightNow = Calendar.getInstance();
Calendar cal = new GregorianCalendar(
rightNow.get(YEAR),
rightNow.get(MONTH),
rightNow.get(DAY_OF_MONTH));
Date now = cal.getTime();
There are other good soln like JodaTime
Ref:
GregorianCalendar
Calendar
Joda Time
I think what you are trying to achieve does not make sense.
A Date object represents time. You can not format it. But, you can get it's string representation in certain format. Like with myFormat.format(today).
I think you're misunderstanding something here about what the Date object is. Date simply holds the information about a point in time - it doesn't have a format at all. When it comes to the String representation of a Date, this is where formatting comes into play. Only worry about the formatting when you are:
Parsing a String representation into a Date object.
Converting a Date back into String representation to display it in a certain way.
Your question doesn't make sense. Formatting a date by definition means converting it to a string using a specific format. The Date object can stay as a Date object. It is only at the point where you wish to convert it to a String that you need to do any formatting.
you cannot associate a format to a Date object instead you can only apply the formats while displaying or other activities,,
Do all processing in the Date object itself and while displaying alone change to the required format,,

Categories