Changing Date type and format - java

I have the below method in which date is coming as parameter that is in form of string and that parameter name is dateString as shown below and ultimately the date is converted and stored n form of java.sql.Date which is also return type of this method.
public static java.sql.Date getSimpleDate11(String dateString) {
if (dateString == null) {
return null;
}
java.util.Date date = null;
java.sql.Date sqlDate = null;
try {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
df.setLenient(false);
date = df.parse(dateString);
sqlDate = new java.sql.Date(date.getTime());
} catch (Exception pe) {
throw new RuntimeException(
"The date entered is invalid or has incorrect format"
+ dateString);
}
return sqlDate;
}
Question:
I found that value is coming in this format 2014-07-23 (YYYY-MM-dd) and I want the return date (java.sql..Date) to be in 23-07-14 (dd-MM-YY).

This generates the date format you want - just use String as the return type instead of java.sql.Date:
public static String getSimpleDate11(String dateString) {
if (dateString == null) {
return null;
}
DateFormat dfIn = new SimpleDateFormat("yyyy-MM-dd");
DateFormat dfOut = new SimpleDateFormat("dd-MM-yy");
try {
Date date = dfIn.parse(dateString);
return dfOut.format(date);
} catch (ParseException e) {
throw new RuntimeException(
"The date entered is invalid or has incorrect format"
+ dateString);
}
}

In case you need to convert the incoming "yyyy-MM-dd" String date to a java.sql.Date object you already did everything right in the code you posted in your question.
A java.sql.Date object, just like a java.util.Date, stores the date you give it internally in some format you, as a programmer, don't have to care about. You just have to know that the date is stored in the object and that you can get it out of the object whenever you need it. If you're interested in technical details you can google for it but, as I said, in your case this doesn't matter.
Whenever you need a java.util.Date object just use the one you get out of your original getSimpleDate11(...) function. Whenever you need a String representation of the date in a certain format, like "dd-MM-yy", take the java.util.Date and plug it into a DateFormat object initialized with the output format you want, just like I did in my first answer with DateFormat dfOut (the format(...) method of DateFormat can handle both, java.util.Date and java.sql.Date objects).

Related

Convert a query’s date return with SimpleDateFormat

I'm trying to convert a resultset from ddMMyyyy HH:mm:ss (ex: 19/06/2022 00:00:10) to yyyyMMddHHmmss (should be 20220619000010) with SimpleDateFormate without success. This is how I'm doing:
I have an Util class, which has the follow class:
public class Utils {
public static String Format(String formato, Date date) {
date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String dataString = sdf.format(date);
return dataString;
}
}
And I also have a ResultSet class witch return the objects of my query based in another class. Example:
Class one:
public class MyFile {
String Date = new String ();
+ getter and setter
}
Class 2 (create the line of my document):
public static MyFile createRow (ResultSet rs) throws SQLException {
MyFile mf = new MyFile();
mf.setDate(Utils.Format(rs.getString("Date");
return mf;
}
The point is: This conversion doesn't work and I can't find another way to do this. Someone could help me, please?
The java message:
"The method Format(String, Date) in te type Utils is not applicable for the arguments (String)
3 quick fixes available:
+ add argument to match 'Format(String, Date)'
- Change method 'Format(String, Date)': Remove parameter 'Date'
º Create method 'Format(String) in type 'Utils'"
For the conversion, you'll need two SimpleDateFormats; one for parsing the string to date, another to turn the date to the desired format:
public static String Format(String formato, Date date) {
SimpleDateFormat inputFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
try {
date = new inputFormat.parse(formato);
} catch (ParseException ex) {
// wrong format?
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String dataString = sdf.format(date);
return dataString;
}
// usage
mf.setDate(Utils.Format(rs.getString("Date"), new Date()));
I presume your date parameter would be a default Date in case the formato input string is invalid.
If you want to do it with the packages java.time and java.time.format you can try something like this. Of course java.util.Date is stored essentially as milliseconds from the epoch without time zone, hence using UTC below. If you want the output to correspond to a particular time zone, then change it:
public static String formatDate(Date d) {
String result = null;
Instant i = Instant.ofEpochMilli(d.getTime());
ZonedDateTime zdt = ZonedDateTime.ofInstant(i, ZoneId.of("UTC"));
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
result = fmt.format(zdt);
return result;
}
First of all, I want to tell you that there are newer and more convenient libraries than the old java.util.Date library. I am not so experienced with the new ones, but mostly java.util.time (like here: Understanding Java util Date) or joda.time are recommended.
So maybe you want to consider using one of the newer library instead of the old SimpleDateFormat from java.util.Date, if you only just began coding with Dates and just picked the first library coming to your mind, I think it could be a good idea.
To your specific problem: The java error message just tells you how it is, in your utils class you have your String Format with the constructor with two input params, a String and a date. In this line:
mf.setDate(Utils.Format(rs.getString("Date");
you are calling your Utils.Format String, but you are only passing one argument, "rs.getString("Date")". So either you refactor your String Format Constructor to only take a string as an argument or you pass (like recommended in the java message) a string and a date, for instance like:
mf.setDate(Utils.Format(rs.getString("Date"), new Date();
While I'm writing this, I think in this line two closing brackets are missing. You should add them.
But I think it should not be that complicated to convert a String like 19/06/2022 00:00:10 into another format using SimpleDateFormat. All you need to do is
String sDate1="19/06/2022 00:00:10";
SimpleDateFormat formatter1=new SimpleDateFormat("yyyyMMddHHmmss");
Date date1=formatter1.parse(sDate1);
This way, in date1 should be your DateString in the Format you specified when initialising your SimpleDateFormat formatter1.
Here is the official doc to SimpleDateFormat: https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Thnx for your answers, but I couldn't make any work.
So, I tried another way with success. It is:
public static String Format (String date) {
String formattedDate= date.substring(0, 4)
+ date.substring(5, 7)
+ date.substring(8, 10)
+ date.substring(11, 13)
+ date.substring(14, 16)
+ date.substring(17, 19);
return formattedDate;
}
mf.setDate(Utils.Format(rs.getString("Date");

convert Date to Time with java

I want to convert a variable of type Date into Time format . I tried to use SimpleDateFormat but without success .
I used the SimpleDateFormat for converting the String into Date.
public static String convDataToString (Date dataconv)
{
SimpleDateFormat formattoData = new SimpleDateFormat("yyyy-MM-dd");
String data = "";
try{
dataconv = formattoData.parse(data);
System.out.println(formattoData.format(dataconv));
}
catch(Exception e){
e.getMessage();
}
return formattoData.format(dataconv);
}
But I need to convert Date into Time format.
In java.util package we can find Date class which encapsulates date and time. If you try new Date(), you get both date and time for the current timestamp. But Calendar class (java.util.Calendar) provides many tools for manipulations of date and time.

How to convert Date to DateTime or LocalDate Joda

I'm like two days on this problem. This is in continuation from this question: convert string to joda datetime gets stuck
I am trying to perform one simple task, to take SQL SERVER ISO 8601 string and convert it to DateTime or LocalDate. I tried everything, but when it comes to the actual conversion with the debugger the program cursor just goes for thinking and never comes back, i.e., the program is stuck there.
I'm so desperate that I even tried to convert that String to Date (which works!) and then convert that Date to DateTime or LocalDate. All had the same result, on the line of the conversion the program looks like stuck in some endless loop (and the fan starts working like crazy).
Here is my so simple function:
public static LocalDate SQLServerIso8601StringToLocalDate(String date) {
LocalDate dateToReturn = null;
DateFormat df = new SimpleDateFormat(CONSTS_APP_GENERAL.SQL_SERVER_DATE_FORMAT);
try {
Date tempDate = (Date) df.parse(date);
DateTime dt = new DateTime(tempDate);
dateToReturn = new LocalDate(tempDate);
} catch (ParseException e) {
// strToReturn = strSqlDate;
}
return dateToReturn;
/*
date = date.replace('T', ' ');
return SimpleIso8601StringToDateTime(date);
*/
//return LocalDate.parse(date, DateTimeFormat.forPattern(CONSTS_APP_GENERAL.SQL_SERVER_DATE_FORMAT));
/* DateTimeFormatter df = DateTimeFormat.forPattern(CONSTS_APP_GENERAL.SQL_SERVER_DATE_FORMAT_WITH_TZ);
return df.parseDateTime(date);
*/ }
This is my String: 2014-01-01T00:00:00
also:
public static final String SQL_SERVER_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss";
Any ideas?
public static Date getDateFromString(String format, String dateStr) {
DateFormat formatter = new SimpleDateFormat(format);
Date date = null;
try {
date = (Date) formatter.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}

Cast string to Date error for return type -ClassCastException

I having method that i move type object (in this time type object is type String)
and i want to cast it to type date how should i do that .
when i use the following code i getting error :
java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Date
Code:
} else if (typeName.equals("Date")) {
return new SwitchInputType<Date>((Date) memberValue);
Something like this should work:
final SimpleDateFormat parsedDate = new SimpleDateFormat("yyyy-MM-dd");
final Date date;
try{
date = parsedDate.parse(stringValue);
} catch(Exception e) {
// handle the exception.
}
How to parse a date?
SimpleDateFormat parserSDF=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = parserSDF.parse(memberValue);
If its a string, you need to parse it. Try using SimpleDateFormat with appropriate format.
Try to create new date object like this Date date = new Date(long) or if you created this string using Date class use its static method Date.valueOf(String s).
You should first convert the string to date object before assigning to a Date. Use SimpleDateFormat.parse() method to parse the string to a Date object.
You can use:
return new SwitchInputType<Date>(new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(memberValue));
You cannot simply cast a String to a Date. To get a Date from a String object which has the String representation of Date, use SimpleDateFormat.
E.g:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); //Change format according to your needs.
Date date = new Date();
try{
date = sdf.parse((String)memberValue); //Update:- memberValue.toString() will also work.
}catch(ParseException pe){
//Do something on Exception.
}
return new SwitchInputType<Date>(date);

Convert String to Date - Date Validation

I am getting a null pointer exception when a user enters date in wrong format.
Method to convert String to Date
Date stringToDate(String dateString) {
Date returnDate = null;
if (dateString!= null && dateString.length() > 0 && isValidDate(dateString)) {
returnDate = dateFormat.parse(dateStr);
}
return returnDate;
}
and
boolean isValidDate(String date) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Pattern datePattern = Pattern.compile("[0-9]{2}/[0-9]{2}/[0-9]{4}");
Matcher datePatternMatch = datePattern.matcher(date);
boolean datePatternMatchfound = datePatternMatch.matches();
if(date==null){
return false;
} else if(date!=null && date.length()>0){
if(datePatternMatchfound){
sdf.setLenient(false);
sdf.parse(date.trim());
}
return true;
} else {
return false;
}
}
I am just curious to know ....
1) what should be valid pattern for date?
2) if the user enters wrong date stringToDate method will certainly get failed and throw a null pointer exception. How to avoid that?
Any help would really be appreciated.
you are assuming the SimpleDateFormat(MM-dd-yyyyas the default pattern the user will input, either you should make sure your user can only enter in SimpleDateFormat, or you should make changes in isValidDate() to accept
Correct format of date representation depends entirely on your application and user locale. You can however limit the input format to a certain format and use it to parse and format the date input.
You can catch the ParseException thrown by the parse method and handle invalid cases inside your catch clause.
For example your code can be simplified to following:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date stringToDate(String dateString) {
try {
Date returnDate = sdf.parse(dateString);
// do something with returnDate, if necessary
return returnDate;
} catch(ParseException e) {
// Date is not valid, handle invalid cases here..
return null; // Not a good practice, you probably would throw an Exception
}
}
And you can use the same formatter to display your values in the user interface by calling sdf.format(someDate) method and getting the String representation.
One thing is that you need to be more defensive in your validation method.
In the code you have shown, you do this:
Matcher datePatternMatch = datePattern.matcher(date);
before you check whether the date String is null. Pattern.matcher(null) results in NullPointerException.
So you need to move this code within your if (date != null) conditional block.
Aside from that, I don't see a benefit in validating the date String with a regex before validating it with a DateFormat. The regex validation is not giving you any additional benefit.
The valid pattern format depends for instance on the country setting of system.
You should put the content of your isValidDate() method in a try-catch block to avoid an exception.
By using Simple date format class we can validate if the string is date or not. You need to make sure to set the setLenient(false) to the simple date format object.
If it's not set you are end up with issue by rounding values.For example, a lenient GregorianCalendar interprets MONTH == JANUARY, DAY_OF_MONTH == 32 as February 1.
Example code:
http://www.vijayakumarg.co.in/2014/04/how-to-validate-date-string-in-java.html
public static boolean validateJavaDate(String strDate)
{
/*
* Set preferred date format,
* For example MM-dd-yyyy, MM.dd.yyyy,dd.MM.yyyy etc.*/
SimpleDateFormat sdfrmt = new SimpleDateFormat("MM/dd/yyyy");
sdfrmt.setLenient(false);
/* Create Date object */
Date javaDate = null;
/* parse the string into date form */
try
{
javaDate = sdfrmt.parse(strDate);
System.out.println("Date after validation: " + javaDate);
}
/* Date format is invalid */
catch (ParseException e)
{
System.out.println("The date you provided is in an " +"invalid date format.");
return false;
}
/* Return 'true' - since date is in valid format */
return true;
}

Categories

Resources