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.
Related
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");
I am able to get all user feed to facebook graph api in my android app. Following is date string from updated_time key :
2014-12-14T18:23:17+0000
First I wasn't able to find format for this string. From google I only come to know, this is might be RFC 2822 date format.
I want to convert this date string to unix time stamp to fetch new user feeds. How can I convert this string to unix time stamp?
If I try to parse this string using following formate I'm getting null date:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
It is advised to strip the +0000 from the date as this is the timezone information. Then handling the timezone separately i.e. as an integer you can either add or subtract it from the time in millis by multiplying the timezone stripped and converting it to milliseconds.
public static long getDateInMillis(String srcDate) {
try {
SimpleDateFormat desiredFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
long dateInMillis = 0;
try {
Date date = desiredFormat.parse(srcDate);
dateInMillis = date.getTime();
return dateInMillis;
} catch (ParseException e) {
e.printStackTrace();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return 0;
}
Your format pattern is wrong.
String timeStamp = "2014-12-14T18:23:17+0000";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.ENGLISH);
System.out.println("Unix timestamp: " + dateFormat.parse(timeStamp).getTime());
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).
I receive date as string from web service in following format 2014-02-27T11:17:00.000Z Could someone tell me how to parse it as Date time object in Java.
I tried parsing it Date.parse() but it didn't work properly.
Then I tried date formatter but it crashes the app. Could someone enlighten me please.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Date d = sdf.parse("2014-02-27T11:17:00.000Z");
You can use dateformat class for that.
DateFormat sdt = new SimpleDateFormat(put your format here);
Date stime= sdt.parse(starttime);
Date etime = sdt.parse(endtime);
Starttime and end time are the strings which you want to parse
Declare a SimpleDateTimeFormat to match your datetime from C# and then use .parse() method on it to get the (Java) Date.
Example:
private static final SimpleDateFormat FORMAT_FULL_DATE = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss'.000Z'"); // replace kk with hh for am/pm format
public static Date getDateTimeFromString(final String string) {
try {
return FORMAT_FULL_DATE.parse(string);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
Is it possible to do format a date of type String using a date formatter? I want to store my Date and Time in the Event class as Strings so that I don't need to convert the Strings loaded from a MYSQL database (using the types DATE and TIME) back into Date types so they can be stored in new Event objects. MySQL only accepts DATE in the format of YYYY-MM-DD and TIME in the format of HH:MM:SS but i want these to be formatted differently when i go to print them out in my program.
When i run this code i get an Cannot format given Object as a Date at java.text.DateFormat.format(Unknown Source) error. If i try using parse() it won't compile because it only accepts Dates.
Main class
public Main() {
ArrayList<Event> events = new ArrayList<Event>();
private SimpleDateFormat timeFormat = new SimpleDateFormat("HH:MM:SS");
private SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-DD");
//Stores current time and date
Date date;
Date time;
String d = "";
String t = "";
d= dateFormat.parse(date);
t= timeFormat.parse(time);
events.add(d, t);
//Print out newly formatted date and time when loaded from mysql
System.out.println(events.get(0).printDate());
System.out.println(events.get(0).printTime());
}
Events class
public class Event {
private String date;
private String time;
public Event(String d, String t) {
date = d;
time = t;
}
public String printDate() {
SimpleDateFormat format = new SimpleDateFormat("DD/MM/YYYY");
String newDate = format.format(date);
return newDate;
}
public String printTime() {
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
String newTime = format.format(time);
return newTime;
}
}
In Event, you should use Date type for date and time field.
This is a more appropriate representation for date and time value. And with them, you can use DateFormat to do whatever formatting you want
(It will be even better to use Joda time LocalDate and LocalTime for your date and time, but that's a bit off topic)
You can't format your dates because they are String objects and SimpleDateFormat needs Date objects.
You should consider a different way of storing them (either as Date or Calendar). See below:
public class Event
{
private Date date;
private Date time;
public Event(String d, String t)
{
String[] details = d.split("\\-");
Calendar c = Calendar.getInstance();
c.set(Integer.parseInt(details[0]), Integer.parseInt(details[1]), Integer.parseInt(details[2]));
date = c.getTime();
details = t.split(":");
c.set(Integer.parseInt(details[0]), Integer.parseInt(details[1]), Integer.parseInt(details[2]));
time = c.getTime();
}
public String printDate()
{
SimpleDateFormat format = new SimpleDateFormat("dd/MM/YYYY");
String newDate = format.format(date);
return newDate;
}
// rest of you class can stay the way it is
}
You can format java.util.Date or java.sql.Date (which is subclass of java.util.Date) using date formatter, eg:
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String dateStr = df.format(date);
Using jdbc ResultSet getDate() method you can obtain java.sql.Date object which you can print in any format using method above
Similar techniques can also be used to parse string in any format into a java.util.Date object
Date date = df.parse(dateStr);
Check the javadoc for the right formatting codes. Try this:
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");