I am using this to get the current time :
java.util.Calendar cal = java.util.Calendar.getInstance();
System.out.println(new java.text.SimpleDateFormat("EEEE, dd/MM/yyyy/hh:mm:ss")
.format(cal.getTime()));
I want to put the value (which I print it) into a date object, I tried this:
Date currentDate = new Date(value);
but eclipse tells me that this function is not good.
Edit
the value is the value that I printed to you using system.out.println
Whenever you want to convert a String to Date object then use SimpleDateFormat#parse
Try to use
String dateInString = new java.text.SimpleDateFormat("EEEE, dd/MM/yyyy/hh:mm:ss")
.format(cal.getTime())
SimpleDateFormat formatter = new SimpleDateFormat("EEEE, dd/MM/yyyy/hh:mm:ss");
Date parsedDate = formatter.parse(dateInString);
.Additional thing is if you want to convert a Date to String then you should use SimpleDateFormat#format function.Now the Point for you is
new Date(String) is deprecated and not recommended now.Now whenever anyone wants to parse , then he/she should use SimpleDateFormat#parse.
refer the official doc for more Date and Time Patterns used in SimpleDateFormat options.
Use SimpleDateFormat parse method:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
String inputString = "11-11-2012";
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date inputDate = dateFormat.parse(inputString, dateFormat );
Since we have Java 8 with LocalDate I would suggest use next:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
String inputString = "11-11-2012";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate inputDate = LocalDate.parse(inputString,formatter);
import java.util.Date;
import java.text.SimpleDateFormat;
Above is the import method, below is the simple code for Date
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
system.out.println((dateFormat.format(date)));
FIRST OF ALL KNOW THE REASON WHY ECLIPSE IS DOING SO.
Date has only one constructor Date(long date) which asks for date in long data type.
The constructor you are using
Date(String s)
Deprecated. As of JDK version 1.1, replaced by DateFormat.parse(String s).
Thats why eclipse tells that this function is not good.
See this official docs
http://docs.oracle.com/javase/6/docs/api/java/util/Date.html
Deprecated methods from your context -- Source -- http://www.coderanch.com/t/378728/java/java/Deprecated-methods
There are a number of reasons why a method or class may become deprecated. An API may not be easily extensible without breaking backwards compatibility, and thus be superseded by a more powerful API (e.g., java.util.Date has been deprecated in favor of Calendar, or the Java 1.0 event model). It may also simply not work or produce incorrect results under certain circumstances (e.g., some of the java.io stream classes do not work properly with some encodings). Sometimes an API is just ill-conceived (SingleThreadModel in the servlet API), and gets replaced by nothing. And some of the early calls have been replaced by "Java Bean"-compatible methods (size by getSize, bounds by getBounds etc.)
SEVRAL SOLUTIONS ARE THERE JUST GOOGLE IT--
You can use date(long date) By converting your date String into long milliseconds and stackoverflow has so many post for that purpose.
converting a date string into milliseconds in java
Try this :-
try{
String valuee="25/04/2013";
Date currentDate =new SimpleDateFormat("dd/MM/yyyy").parse(valuee);
System.out.println("Date is ::"+currentDate);
}catch(Exception e){
System.out.println("Error::"+e);
e.printStackTrace();
}
Output:-
Date is ::Thu Apr 25 00:00:00 GMT+05:30 2013
Your value should be proper format.
In your question also you have asked for this below :-
Date currentDate = new Date(value);
This style of date constructor is already deprecated.So, its no more use.Being we know that Date has 6 constructor.Read more
Here is the optimized solution to do it with SimpleDateFormat parse() method.
SimpleDateFormat formatter = new SimpleDateFormat(
"EEEE, dd/MM/yyyy/hh:mm:ss");
String strDate = formatter.format(new Date());
try {
Date pDate = formatter.parse(strDate);
} catch (ParseException e) { // note: parse method can throw ParseException
e.printStackTrace();
}
Few things to notice
We don't need to create a Calendar instance to get the current date
& time instead use new Date()
Also it doesn't require 2 instances of SimpleDateFormat as
found in the most voted answer for this question. It's just a
waste of memory
Furthermore, catching a generic exception like Exception is a bad practice when we know that the parse method only stands a chance to throw a ParseException. We need to be as specific as possible when dealing with Exceptions. You can refer, throws Exception bad practice?
try this, it worked for me.
String inputString = "01-01-1900";
Date inputDate= null;
try {
inputDate = new SimpleDateFormat("dd-MM-yyyy").parse(inputString);
} catch (ParseException e) {
e.printStackTrace();
}
dp.getDatePicker().setMinDate(inputDate.getTime());
It is because value coming String (Java Date object constructor for getting string is deprecated)
and Date(String) is deprecated.
Have a look at jodatime or you could put #SuppressWarnings({“deprecation”}) outside the method calling the Date(String) constructor.
What you're basically trying to do is this:-
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
The reason being, the String which you're printing is just a String representation of the Date in your required format. If you try to convert it to date, you'll eventually end up doing what I've mentioned above.
Formatting Date(cal.getTime()) to a String and trying to get back a Date from it - makes no sense. Date has no format as such. You can only get a String representation of that using the SDF.
Related
I have english date coming in string format such as 2011-12-12.
I need to convert it into Date format so I tried :
String assignDates="2011-12-12";
DateFormat df = new SimpleDateFormat("YYYY-MM-dd");
Date dates = df.parse(assignDates);
cstmt.setDate(2,dates);
But i need to set it into cstmt.setDate(2,dates); but it is showing me error in this line like this:
The method setDate(int, java.sql.Date) in the type PreparedStatement
is not applicable for the arguments (int, java.util.Date)
The full code is:
public String getConvertedDateToBs(String assignDates) {
try
{
DateFormat df = new SimpleDateFormat("YYYY-MM-dd");
System.out.println("yo ni chiryo"+assignDates);
conn = DriverManager.getConnection(dbProperties.getDatabaseUrl());
System.out.println("chiryoassignDatea");
CallableStatement cstmt = conn.prepareCall("{? = call PCFN_LIB_ETON(?)}");
cstmt.registerOutParameter(1,Types.VARCHAR);
//java.sql.Types.VARBINARY
Date dates = df.parse(assignDates);
cstmt.setDate(2,dates);
cstmt.executeUpdate();
dateInBs = cstmt.getString(1);
/*dateInBs = df.format(assignBsDate);*/
System.out.println(dateInBs);
}
catch (SQLException e)
{
System.err.println(e.getMessage());
}
return dateInAd;
}
Assuming you are using at least JDBC version 4.2 (which you probably are), it’s much easier and more straightforward than you think (not tested):
LocalDate date = LocalDate.parse(assignDates);
cstmt.setObject(2, date);
No need for DateFormat/SimpleDateFormat and no need for java.util.Date nor java.sql.Date. Which is very good because those classes had design problems, the first in particular are notoriously troublesome. All of these old classes are considered long outdated.
Instead use LocalDate from java.time, the modern Java date and time API. The modern API is much nicer to work with.
I am taking advantage of the fact that your string, 2011-12-12, is in ISO 8601 format, the format that the modern date and time classes parse (and also print) as their default, that is, without any explicit formatter.
This question already has answers here:
Java Date Error
(8 answers)
Closed 4 years ago.
I want to convert String values in the format of mm/dd/yy to YYYY-MM-DD Date. how to do this conversion?
The input parameter is: 03/01/18
Code to convert String to Date is given below
public static Date stringToDateLinen(String dateVlaue) {
Date date = null;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
try {
date = formatter.parse(dateVlaue);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
When tried to convert using this method it shows the following error
java.text.ParseException: Unparseable date: "03/01/18"
As you say the input is in a different format, first convert the String to a valid Date object. Once you have the Date object you can format it into different types , as you want, check.
To Convert as Date,
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy");
date = formatter.parse(dateVlaue);
To Print it out in the other format,
SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd");
dateString = formatter1.format(date)
You are writing it the wrong way. In fact, for the date you want to convert, you need to write
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy");
The format you are passing to SimpleDateFormat is ("yyyy-MM-dd") which expects date to be in form 2013-03-01 and hence the error.
You need to supply the correct format that you are passing your input as something like below
public static Date stringToDateLinen(String dateVlaue) {
Date date = null;
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yy");
try {
date = formatter.parse(dateVlaue);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
The solution for the above problem
Convert the String date value in the Format of "dd/mm/yy" to Date.
By using the converted Date can able to frame the required date format.
The method has given below
public static String stringToDateLinen(String dateVlaue) {
Date date = null;
SimpleDateFormat formatter = new SimpleDateFormat("dd/mm/yy");
String dateString = null;
try {
// convert to Date Format From "dd/mm/yy" to Date
date = formatter.parse(dateVlaue);
// from the Converted date to the required format eg : "yyyy-MM-dd"
SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd");
dateString = formatter1.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return dateString;
}
EDIT: Your question said “String values in the format of mm/dd/yy”, but I understand from your comments that you meant “my input format is dd/mm/yy as string”, so I have changed the format pattern string in the below code accordingly. Otherwise the code is the same in both cases.
public static Optional<LocalDate> stringToDateLinen(String dateValue) {
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yy");
try {
return Optional.of(LocalDate.parse(dateValue, dateFormatter));
} catch (DateTimeParseException dtpe) {
return Optional.empty();
}
}
Try it:
stringToDateLinen("03/01/18")
.ifPresentOrElse(System.out::println,
() -> System.out.println("Could not parse"));
Output:
2018-01-03
I recommend you stay away from SimpleDateFormat. It is long outdated and notoriously troublesome too. And Date is just as outdated. Instead use LocalDate and DateTimeFormatter from java.time, the modern Java date and time API. It is so much nicer to work with. A LocalDate is a date without time of day, so this suites your requirements much more nicely than a Date, which despite its name is a point in time. LocalDate.toString() produces exactly the format you said you desired (though the LocalDate doesn’t have a format in it).
My method interprets your 2-digit year as 2000-based, that is, from 2000 through 2099. Please think twice before deciding that this is what you want.
What would you want to happen if the string cannot be parsed into a valid date? I’m afraid that returning null is a NullPointerException waiting to happen and a subsequent debugging session to track down the root cause. You may consider letting the DateTimeParseException be thrown out of your method (just declare that in Javadoc) so the root cause is in the stack trace. Or even throw an AssertionError if the situation is not supposed to happen. In my code I am returning an Optional, which clearly signals to the caller that there may not be a result, which (I hope) prevents any NullPointerException. In the code calling the method I am using the ifPresentOrElse method introduced in Java 9. If not using Java 9 yet, use ifPresent and/or read more about using Optional elsewhere.
What went wrong in your code?
The other answers are correct: Your format pattern string used for parsing needs to match the input (not your output). The ParseException was thrown because the format pattern contained hyphens and the input slashes. It was good that you got the exception because another problem is that the order of year, month and day doesn’t match, neither does the number of digits in the year.
Link
Oracle tutorial: Date Time explaining how to use java.time.
I have very simple question - I read couple of threads here but I still do not understand how to get simple thing. I want to send string to method and get back joda date. I had no problem to build it up, but return format is 2015-03-11T17:13:09:000+01:00. How can I get desired (e.g. mmm-dd hh:mm) format back from below mentioned method (it mustto be a dateTime for sorting purposes on FX form)? I tried to gamble with another dateTimeFormatter but had no luck. Thank you very much in advance
public static DateTime stringToDateTime(String textDate) throws ParseException
{
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS");
DateTime jodaTime = dateTimeFormatter.parseDateTime(textDate);
return jodaTime;
}
What do you mean by "return format"? "Format" term here could only be related to a string representation of a DateTime object. That means you should specify format of your input string (what you've already done in your code) - and a corresponding DateTime object will be created. After that you probably use toString() to check the results, but DateTime.toString() uses ISO8601 format (yyyy-MM-ddTHH:mm:ss.SSSZZ) according to JavaDoc - that gives you your 2015-03-11T17:13:09:000+01:00 result.
So to get it as desired you could try using toString(String pattern) method with format you need. But once again - it's just an output format to convert DateTime to String, it doesn't affect the datetime stored in your DateTime object.
I just use Calendar object so this is a possible way to do it:
static String stringToDateTime(String textDate) {
Calendar c = new GregorianCalendar();
// How you want the input to be formatted
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date = df.parse(textDate);
c.setTime(date);
} catch (ParseException e) {
e.printStackTrace();
}
// How do you want to print your date
df= new SimpleDateFormat("dd-MM-yy");
return df.format(c.getTime());
}
// input
String myDate = "2015-04-15 14:25:25";
System.out.println(stringToDateTime(myDate));
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')
This question already has answers here:
How to convert ISO 8601 date (string) to Date?
(3 answers)
Closed 5 years ago.
How can I convert a String object to a Date object?
I think I need to do something like this:
Date d=(some conversion ) "String "
Any help would be greatly appreciated.
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
Date date = dateFormat.parse("1.1.2001");
For details refer to: SimpleDateFormat documentation
Date-to-String conversion is a relatively complex parsing operation, not something you can do with a simple cast as you are trying.
You'll have to use a DateFormat. It can be as simple as:
Date d = DateFormat.getDateInstance().parse("09/10/2009");
But this changes the expected date format depending on the locale settings of the machine it's running on. If you have a specific date format, you can use SimpleDateFormat:
Date d = new SimpleDateFormat("d MMM yyyy HH:mm").parse("4 Jul 2001 12:08");
Note that the parse method will always expect one specific format, and will not try to guess what could be meant if it receives a different format.
See Sun's Java tutorial and the class SimpleDateFormat
Use a SimpleDateFormat with a format string, which matches your actual format:
SimpleDateFormat sdf =
new SimpleDateFormat("yyyy-MM-dd");
Date d = sdf.parse("2009-10-09");
java.text.SimpleDateFormat that extends java.text.DateFormat abstract class.
DateFormat MYDate = new SimpleDateFormat("dd/MM/yyyy");
Date today = MYDate.parse("09/10/2009");
you should parse the string with the SimpleDateFormat class
use
Date date = DateFormat.getInstance.parse( dateString );
You can convert String object into Date object using this method. and this Java code is tested and running component in my environment.
public static Date parseStringAsDate(String dateStr, String format) throws ParseException
{
if(null==dateStr || "".equals(dateStr))
throw new IllegalArgumentException("dateStr must not be null or empty");
DateFormat df = new SimpleDateFormat(format);
return df.parse(dateStr);
}
dateStr = "17/05/2017"
format= "dd/MM/yyyy"