Java String to Date without time - java

I'm taking a class in Java and I need to convert a string to a date format (dd/MM/yyyy). I have been using the SimpleDateFormat to format my input, but it is showing the time, timezone and day of the week the date falls. Here is a snippet of my code:
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
do{
y = JOptionPane.showInputDialog(null,
"Please enter the vehicle's registration date",
"Year?",
JOptionPane.QUESTION_MESSAGE);
try {
date = df.parse(y);
check = true;
}
catch (ParseException e) {
check = false;
}
}
while (check == false);
return date;
Anyone know how I can keep the format to just the date (e.g. 12/3/2000)?
Thanks

Just format it accordingly using SimpleDateFormat#format().
String dateString = new SimpleDateFormat("dd/MM/yyyy").format(dateObject);
The java.util.Date object contains information about both date and time. If you want only the date part in a human representable format, then you need to format it into a String. Invoking Date#toString() as you would get when doing System.out.println(dateObject) would only return the date in format dow mon dd hh:mm:ss zzz yyyy. Also see the linked javadoc.

I have a similar solution to #BalusC, except this one will provide a locale-dependent formatting:
String dateString = java.text.DateFormat.getDateInstance().format(dateObject);
In other words your US and EU customers will get different formatting. One they're familiar with.

Related

Unparseable date with SimpleDateFormatter

I have a date that keeps giving me an error of
java.text.ParseException: Unparseable date: " 5 April 2017  "
All other dates (without word months) work fine
The code I am using is below:
VisitDate=VisitDate.trim();
if (VisitDate.matches(".*[a-z].*")){
SimpleDateFormat changeDate = new SimpleDateFormat("dd_MMM_yy", Locale.UK);
//Convert the string to a date
Date date = changeDate.parse(VisitDate);
//Reformat the date the way I like it
SimpleDateFormat dt1 = new SimpleDateFormat("dd_MM_yy");
//Convert back into a string
try {
VisitDate=dt1.format(date);
if(VisitDate==null){
SimpleDateFormat dt2 = new SimpleDateFormat("dd MM yy");
//Convert back into a string
VisitDate=dt2.format(date);
if(VisitDate==null){
SimpleDateFormat dt3 = new SimpleDateFormat("dd MMMM yy");
//Convert back into a string
VisitDate=dt3.format(date);
if(VisitDate==null){
SimpleDateFormat dt4 = new SimpleDateFormat("d_MMM_yy");
//Convert back into a string
VisitDate=dt4.format(date);
if(VisitDate==null){
SimpleDateFormat dt5 = new SimpleDateFormat("d_MMMM_yy");
//Convert back into a string
VisitDate=dt5.format(date);
if(VisitDate==null){
SimpleDateFormat dt6 = new SimpleDateFormat("dd_MMM_yy");
//Convert back into a string
VisitDate=dt6.format(date);
if(VisitDate==null){
SimpleDateFormat dt7 = new SimpleDateFormat("dd_MMM_yyyy");
//Convert back into a string
VisitDate=dt7.format(date);
if(VisitDate==null){
SimpleDateFormat dt8 = new SimpleDateFormat("dd_MMMM_yyyy");
//Convert back into a string
VisitDate=dt8.format(date);
if(VisitDate==null){
VisitDate=VisitDate.replaceAll("\\s", "");
SimpleDateFormat dt9 = new SimpleDateFormat("dd MMMM yyyy");
//Convert back into a string
VisitDate=dt9.format(date);
}
}
}
}
}
}
}
}
} catch (Exception e) {
Logger.error(e+"->No visit Date frmo here with the original date as: "+date);
}
}
Happy to read your expressed interest in the modern date and time classes, here’s just a snippet to get you started:
String visitDate = " 5 April 2017 ";
DateTimeFormatter parseFormatter
= DateTimeFormatter.ofPattern("d MMMM uuuu", Locale.UK);
visitDate = visitDate.trim();
LocalDate date = LocalDate.parse(visitDate, parseFormatter);
// reformat to the string we like
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd_MM_uu");
visitDate = date.format(formatter);
The result is
05_04_17
I have spelled visitDate with a small v since the Java coding conventions recommend that variable names begin with a small letter.
The uu is subtle and probably something you can ignore. It’s a signed year where 0 equals 1 BC, -1 equals 2 BC and so forth. Assuming none of your dates are that old, you can use u and y interchangeably.
I believe that neither SimpleDateFormat.format() nor LocalDate.format() will ever return null, so all your null checks are superfluous.
Link for further reading: Oracle tutorial: Trail: Date Time
You only have one SimpleDateFormatter being used for parsing:
SimpleDateFormat changeDate = new SimpleDateFormat("dd_MMM_yy", Locale.UK);
//Convert the string to a date
Date date = changeDate.parse(VisitDate);
It is using the format dd_MMM_yy, however you are passing 4 digits for the year.
The rest of your SimpleDateFormatters are being used for formatting to a string, not parsing from a string. Only the first one will be called, since it will be able to produce a string given a valid date, and the following null checks will stop any other formatters from being used.
You have the input string to parse like this: " 5 April 2017 ". But you have no pattern match for this input
First please trim the space of input string
Second please change the format of your string or add another pattern to parse this string, because you have month April with 5 letter, but you have no pattern with MMMMM. Usually the month will be shorten to 3 letter like: April -> Apr, March -> Mar ...

Java DateFormat conversion automatically increases hour by 1

I am trying to take date in string and its input format string and converting the date in output format. However after conversion into Date, the java code increases the number of hours by one. I am not able to understand what causes the bug.
My Code:
try {
DateFormat outputFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
DateFormat inputFormat = new SimpleDateFormat(format);
Date date = inputFormat.parse(parameterValue);
parameterValue = outputFormat.format(date);
return parameterValue;
} catch (ParseException ex) {
// take action
}
format string: ddMMMyyyy / hh:mm z
Input Date: 07DEC2015 / 10:02 GMT
Output Date: 07/12/2015 11:02:00
outputFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
resolved it.
If you don't want to use timezone, in java 8 you can use LocalDate/LocalTime/LocalDateTime:
LocalDateTime localDateTimeInstance = LocalDateTime.parse(dateToBeConverted, DateTimeFormatter.ofPattern(formatOfDateToBeConverted));
return localDateTimeInstance.format("dd/MM/yyyy hh:mm:ss");
/*
Also check out ZoneDate, ZoneTime (for timezone)
Checkout - LocalDate, LocalTime
*/

Get Date object from String in form 2012-07-26 23:59:59

I have the input string as 2012-07-27 and I want the output as Date but with the same format like 2012-07-27
Code
DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
Date today = df.parse("20-12-2005 23:59:59");
System.out.println("Today = " + df.format(today));
} catch (ParseException e) {
e.printStackTrace();
}
Output
20-12-2005 23:59:59
But it's string object I want the same output (20-12-2005 23:59:59) as date object not as string object.
How can I get the Date in the form DD-MM-YYYY HH:MM:SS?
Date today is the date object you get for input String. There are nothing like formatted dates in Java. Date is always just date object. You perform all sorts of operations on that date object and when you want to Store (or) display just apply format()
df.format(today) // is just for formatting and display purpose.
There is difference in your format passed to SimpleDateFormat and way you are passing date string. You should Also use HH
DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
try {
Date today = df.parse("20-12-2005 23:59:59");
System.out.println("Today = " + df.format(today));
//To Print Real Today
System.out.println("Real Today = " + df.format(new Date()));
} catch (ParseException e) {
e.printStackTrace();
}
The Date class has many deprecated methods and the only correct way to create it right now is via a long (read doc for details).
You should look into GregorialCalendar where you can pass some constant fields of Calendar as attributes.
If you want to input the date from your String, I would either do a custom parser that creates a calendar or something like this.
Hope I helped :)

Java ParseException while attempting String to Date parsing

I'm having a hard time Parsing/Formatting a Date string received back from a web service. I've attempted multiple approaches, but with no luck.
Sample Date String:
2011-10-05T03:00:00Z
Exception:
W/System.err(10072): java.text.ParseException: Unparseable date: "2011-10-05T05:00:00Z" (at offset 10)
W/System.err(10072): at java.text.DateFormat.parse(DateFormat.java:626)
Sample Code:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:SSSS");
Date date = formatter.parse(info.AiringTime);
I've found that if I remove the "T" between the date and the time and replace it with a space, it will format just fine. Anybody have any suggestions?
--UPDATE--
After looking deeper into the API documentation, I found this:
All response DateTime values are in UTC format. You need to apply the UTC offset to calculate the local time for display.
DateTime is a date-and-time value specified in one of the following formats:
UTC format: YYYY-MM-DDThh:mm:ssZ. For example: 2011-03-15T02:00:00Z.
Local time with an offset: YYYY-MM-DDThh:mm:ss + or - hh:mm (positive or negative offset). For example, for US Pacific time: 2011-03-14T06:00:00 -08:00.
Any suggestions on the UTC format approach?
You could try:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
String dateString = dateString.replace("Z", "GMT+00:00");
Date date = dateFormat.parse(dateString);
The above code should correctly handle the case where a timezone is specified in the date. As Z represents the UTC/GMT timezone it is replaced by GMT so the SimpleDateFormat can interpret it correctly (i would love to know a cleaner way of handling this bit if anyone knows one).
Try,
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
This pattern should parse the date you provide: "yyyy-MM-dd'T'HH:mm:ss'Z'".
If you want to use SimpleDateFormat and you have a limited number of variations, you can create separate formatters for each pattern and chain them:
Date date = formatter1.parse(info.AiringTime);
if (date == null)
{
date = formatter2.parse(info.AiringTime);
if (date == null)
{
date = formatter2.parse(info.AiringTime);
if (date == null)
{
date = formatter3.parse(info.AiringTime);
}
}
}
or put them in a list and iterate until non-null or no more formatters.
If you have too many patterns for this to be practical, you can parse it yourself or try one of these libraries.
This worked for me
SimpleDateFormat isoDateFormat = new SimpleDateFormat("yyyy-mm-dd'T'hh:mm:ss'Z'");
SimpleDateFormat viewFriendlyDateFormat = new SimpleDateFormat("dd/MMM/yyyy hh:mm:ss aaa");
String viewFriendlyDate = "";
try {
Date date = isoDateFormat.parse(timestamp);
viewFriendlyDate = viewFriendlyDateFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat isoDateFormat = new SimpleDateFormat("yyyy-mm-dd'T'hh:mm:ss'Z'");
SimpleDateFormat viewFriendlyDateFormat = new SimpleDateFormat("dd/MMM/yyyy hh:mm:ss aaa");
String viewFriendlyDate = "";
try {
Date date = isoDateFormat.parse(timestamp);
viewFriendlyDate = viewFriendlyDateFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}

Date conversion in Java

How can I take a string in a format such as: 2008-06-02 00:00:00.0 and convert it to: 02-Jun-2008?
Can I somehow take the original string, convert it to a Date object, then use a formatter to get the final output (rather than parsing the string myself)? Thanks!
You can use SimpleDateFormat to convert between a String and a Date object and vice versa based on a pattern. Click the API link, you'll see patterns being explained in detail. A 4-digit year can be represented with yyyy, a 3-character month abbreviation can be represented with MMM and so on.
First you need to parse the String of the first format into a Date object:
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date date = sdf1.parse(inputString);
Then you need to format the Date into a String of the second format:
SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH);
String outputString = sdf2.format(date);
Note that you need to take the Locale into account as well to get the month to be printed in English, else it will use the platform's default locale to translate the month.
Use 2 instances of SimpleDateFormat class. One for converting your input string to date and second to convert date back to string but in another format.
Here is an example of using SimpleDateFormat.
DateFormat startFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
DateFormat endFormat = new SimpleDateFormat("dd-MM-yyyy");
String outputString = null;
try {
Date date = startFormat.parse(inputString);
outputString = endFormat.format(date);
} catch(ParseException pe) {
throw new IllegalArgumentException(inputString + " is not properly formated.", pe);
}
You can definitely use SimpleDateFormat class like others have recommended.
Another suggestion if it applies in your case. If you are getting this data from a sql query you can also use to_char() method to format it in the query itself. For example: to_char(column_name,'DD-MON-YYYY')

Categories