Cast String Date to new format Java - java

I am trying to cast a date format which is string resultset from database to a standard format, but using simpledateformat gives following error:
Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object as a Date
at java.text.DateFormat.format(Unknown Source)
at java.text.Format.format(Unknown Source)
at CopyEJ.CopyEJ.main(CopyEJ.java:113)
RROR: JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2
JDWP exit error AGENT_ERROR_NO_JNI_ENV(183): [../../../src/share/back/util.c:838]
With De-bug I found out variable time_stmp has value "2013-04-19 17:29:06" I want to cast to this:
yyyyMMddhhmmss
Here's code:
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");
ResultSet rs_dt = cmd1.executeQuery(dt);
String time_stmp = null;
while (rs_dt.next())
{
time_stmp = rs_dt.getString(1);
}
StringBuilder ts = new StringBuilder( df.format( time_stmp ) );
What is the best way to achieve this?

Your Simple DateFormat has the wrong datepattern. You have to parse it to date with the pattern of you DB, then parse it back to String.
Try it this way:
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
ResultSet rs_dt = cmd1.executeQuery(dt);
String time_stmp = null;
while (rs_dt.next())
{
time_stmp = rs_dt.getString(1);
}
Date d = null;
try {
Date d = df.parse(time_stmp);
} catch (ParseException ex) {
Logger.getLogger(Prime.class.getName()).log(Level.SEVERE, null, ex);
}
SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddhhmmss");
StringBuilder ts = new StringBuilder( df2.format(d) );
By the way:
If you want your output to be in 24h-Format, then you have to use the pattern yyyyMMddHHmmss

The problem is, format of the date retrieved from DB is yyyy-dd-MM HH:mm:ss and you are trying to parse it with the format yyyyMMddhhmmss
You can do something like this
String date = "2013-04-19 17:29:06";
Date d = new SimpleDateFormat("yyyy-dd-MM HH:mm:ss").parse(date);
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyyMMddhhmmss");
System.out.println(outputFormat.format(d));

You need to use DateFormat.parse() here since the argument is of type String. DateFormat.format() on the other hand is used to format Date objects as String.
StringBuilder ts = new StringBuilder(df.format(df.parse(time_stmp)));
Also, it's recommended to save date/time data as a TimeStamp in database instead of a String.

Like it was mention you need to use
SimpleDateFormat.parse()
Also if your string is in the form
`2013-04-19 17:29:06`
You will want to construct your SimpleDateFormat for reading in like this
`yyyy-MM-dd HH:mm:ss` //make sure you use uppercase H for 24 hour times

Use SimpleDateFormat.parse() to convert a String to a Date.
Use SimpleDateFormat.format() to convert a Date to a String.
All together now:
SimpleDateFormat dbFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat stdFormat = new SimpleDateFormat("yyyyMMddhhmmss");
String s = stdFormat.format(dbFormat.parse(input));
You can modify the formats to suit your needs.

Hi you can use below code to format date as of your choice (Ex: yyyy-MM-dd HH:mm:ss)
Calendar calendar = Calendar.getInstance();
Date calDate = calendar.getInstance().getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("Calendar Date: " + calDate);
System.out.println("Your Choice Date format (yyyy-MM-dd HH:mm:ss): "+dateFormat.format(calDate));

This will work
SimpleDateFormat df = new SimpleDateFormat("YYYY-MM-dd hhhh:mm:ss");
String time_stmp ="2013-04-19 17:29:06";
Date date=df.parse(time_stmp);
StringBuilder ts = new StringBuilder( df.format( date ) );
System.out.println(ts);

Related

get current date time in yyyy-MM-dd hh.mm.ss format

I have an application which will ALWAYS be run in only one single time zone, so I do not need to worry about converting between time zones. However, the datetime must always be printed out in the following format:
yyyy-MM-dd hh.mm.ss
The code below fails to print the proper format:
public void setCreated(){
DateTime now = new org.joda.time.DateTime();
String pattern = "yyyy-MM-dd hh.mm.ss";
created = DateTime.parse(now.toString(), DateTimeFormat.forPattern(pattern));
System.out.println("''''''''''''''''''''''''''' created is: "+created);
}
The setCreated() method results in the following output:
"2013-12-16T20:06:18.672-08:00"
How can I change the code in setCreated() so that it prints out the following instead:
"2013-12-16 20:06:18"
You aren't parsing anything, you are formatting it. You need to use DateTimeFormatter#print(ReadableInstant).
DateTime now = new org.joda.time.DateTime();
String pattern = "yyyy-MM-dd hh.mm.ss";
DateTimeFormatter formatter = DateTimeFormat.forPattern(pattern);
String formatted = formatter.print(now);
System.out.println(formatted);
which prints
2013-12-16 11.13.24
This doesn't match your format, but I'm basing it on your code, not on your expected output.
public static void main(String args[])
{
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//dd/MM/yyyy
Date now = new Date();
String strDate = sdfDate.format(now);
System.out.println(strDate);
}
out put 2013-12-17 09:48:11
try this
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss");
Date now = new Date();
String strDate = sdfDate.format(now);
System.out.println(strDate);
demo
Try this:
org.joda.time.DateTime now = new org.joda.time.DateTime();
String pattern = "yyyy-MM-dd hh.mm.ss";
DateTimeFormatter formatter = DateTimeFormat.forPattern(pattern);
String formatted = formatter.print(now);
LocalDateTime date = formatter.parseLocalDateTime(formatted);
System.out.println(date.toDateTime());
And now in Java 9, you can use this:
LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh.mm.ss"));

Date convert in Java

I want to compare two dates, for that i convert the string to date format.But during the conversion the date format changed to "02/01/2013" and "03/01/2014".It makes error in my logic.any one please tell me to how to compare two days in my date format.
String fdate="01/02/2012";
String tdate="01/03/2013";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date frmdt=new Date(fdate);
String s1 = sdf.format(frmdt);
Date todt=new Date(tdate);
String s2 = sdf.format(todt);
Date frmdate = sdf.parse(s1);
Date todate = sdf.parse(s2);
if(frmdate.compareTo(todate)<=0){
//process;
}
Try this:
String fs = "01/02/2012";
String ts = "01/03/2013";
DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
sdf.setLenient(false);
Date fdate = sdf.parse(fs);
Date tdate = sdf.parse(ts);
if (fdate.before(tdate) || f.date.equals(tdate)) {
//process;
}
You've got too much going on. It's much simpler.
It seems to me that you should be calling SimpleDateFormat.parse instead:
// Using the US locale will force the use of the Gregorian calendar, and
// avoid any difficulties with different date separator symbols etc.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("UTC")); // Avoid DST complications
sdf.setLenient(false);
Date fromDate = sdf.parse(fromDateText);
Date toDate = sdf.parse(toDateText);
// Alternatively: if (!fromDate.after(toDate))
if (fromDate.compareTo(toDate) <= 0) {
...
}
I'd actually suggest that you use Joda Time if at all possible, where you could use a LocalDate type to more accurately represent your data.
You're doing it wrong :)
String fdate="01/02/2012";
String tdate="01/03/2013";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date frmdate = sdf.parse(fdate);
Date todate = sdf.parse(tdate);
if(frmdate.compareTo(todate)<=0){
//process;
}
You were passing to Date a not parsed date with your format. Also Date(String) is deprecated. DateFormat.parse(String) is the correct one.

Date error in android to store in sqlite

I am trying to in insert date into sqlite using:
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
String data = format.format(new Date(19900101));
System.err.println("Time is.."+format.format(19900101));
But i am getting 19700101 in log. i am getting same result even if i change the dates as 20000101 or any thing.
Any one suggest me why it happens?
the code is wrong
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
Date data = format.parse("19900101");
System.out.println("Time is.."+data );
when u use new Date(123) it expects some time in milliseconds i think
Change your code as for formatting current string to date :
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
Date convertedDate = (Date) format.parse("19900101");
SimpleDateFormat formats = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String fmconvertedDate =formats.format(convertedDate);
System.err.println("Time is.."+fmconvertedDate);
and output is :
Time is..1990-01-01 00:00:00

Simple java date conversion

Having some troubles and can't find a quick answer..
Im trying to store a date within a string, and later fetch it to convert it back to a date.
However when storing the date using:
string tmp = new Date().toString();
And then trying to convert it back using
Date date = new Date(tmp);
I get the Exception type
java.lang.IllegalArgumentException
with my Android 2.2 device. Does work with 2.2 & 2.3 emus tho.
Any tips on what other way i can store and convert back?
You could use SimpleDateFormat with its methods parse() and format().
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SSS");
String tmp = sdf.format(new Date());
Date date = sdf.parse(tmp);
Do you need it to be a string? long is easier :)
do
long time = new Date().getTime();
Date date = new Date(time);
then you dont' have to parse
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
// to string
String dateStr = formatter.format(new Date());
// to date
Date date = formatter.parse(dateStr);
use SimpleDateFormat as shown below.
SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd");
//this will convert date into string.
String temp = formatter.format(currentDate.getTime());
//this will convert string into date format.
Date date=(Date)formatter.parse(temp);

String to Date in Java

HI,
I am converting String to Date format. But it returns wrong dates. for example,
String startDate = "08-05-2010"; // (MM/dd/yyyy)
I want to convert this to "Date" object like this, 05-JUL-10
How to do that? I tried like this
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yy");
scal1.setTime(dateFormat.parse((startDate)));
but i am getting "Unparseable date:" .
If you want to convert a date string of one format to another format, you can use format() and parse() methods of SimpleDateFormat class
First you need to parse the string to a date object using parse() method setting the source pattern and then format the date object using format() method setting the target pattern:
SimpleDateFormat sourceFormat = new SimpleDateFormat("MM-dd-yyyy");
Date sourceFormatDate = sourceFormat.parse("08-05-2010");
SimpleDateFormat destFormat = new SimpleDateFormat("dd-MMM-yy");
String destFormatDateString = destFormat.format(sourceFormatDate);
System.out.println(destFormatDateString); // 05-Aug-10
Unless you've left something out, it looks like you're trying to parse it with the wrong format, i.e. you have an mm-dd-yyyy, and you're trying to parse it with the format dd-MMM-yy. Try a separate date format for what you're parsing from what you're encoding.
SimpleDateFormat format = new SimpleDateFormat(“yyyy-MM-dd”);
String strDate = “2007-12-25″;
Date date = null;
try {
date = format.parse(strDate);
} catch (ParseException ex) {
ex.printStackTrace();
}
The format dd-MMM-yy you use to parse the string is wrong; the format should be dd-MM-yyyy.
String startDate = "08-05-2010";
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = dateFormat.parse((startDate));
Note that Date objects themselves do not have a format: a Date objects just represents a date and time value, just like an int is just a number, and doesn't have any inherent formatting information. If you want to display the Date in a certain format, you'll have to use a DateFormat object again to format it:
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yy");
System.out.println(dateFormat.format(date));
// output: 08-May-10

Categories