How to get Date format like this?
Saturday,Dec 11,2011
Edited:
My code portion is like the following:
String outDate = "";
Date dT = new Date(year, mon, day);
SimpleDateFormat sdf = new SimpleDateFormat("EEE,MMM dd,yyyy");
outDate = sdf.format(dT);
and its output is `Sat,Dec 02,3911` when year = 2011,mon = 11,day = 2;
what is the reason of giving wrong month and year in output?
You can use SimpleDateFormat.
Try:
SimpleDateFormat formatter = new SimpleDateFormat("EEEE,MMM dd,yyyy");
String text = formatter.format(...);
That will use the default locale - adjust accordingly for a different one.
Try to use this function
Date today=new Date();
public String getCurrentTime()
{
SimpleDateFormat sdf = new SimpleDateFormat("EEEE,MM,dd,YYYY");
String ClsCurrentDay = sdf.format(today);
return ClsCurrentDay;
}
Related
I have date as a string like this
String date = "11-12-2018"
I want to change it to "2018-12-11"
with the same variable. So, I tried the code below but it doesn't give me the output I expect.
String date = "11-12-2018"
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date d = df.parse(date);
results in:
"0012-06-09"
I want
"2018-12-11"
You can do this 3 ways. First is using SimpleDateFormat and Date and second using DateTimeFormatter and LocalDate and third you can use Split.
1. Using Date and SimpleDateFormat
String date = "11-12-2018";
SimpleDateFormat df = new SimpleDateFormat("dd-mm-yyyy");
java.util.Date d = df.parse(date);
String finalDate = new SimpleDateFormat("yyyy-MM-dd").format(d);
System.out.println(finalDate);
Here we have our actual date String date = "11-12-2018"; we know we want to change it to 2018-12-11
So lets parse that date into a Date object using this code
SimpleDateFormat df = new SimpleDateFormat("dd-mm-yyyy");
java.util.Date d = df.parse(date);
Okay so now we have a date object of our actual date, Now lets format it to our new date.
String finalDate = new SimpleDateFormat("yyyy-MM-dd").format(d);
2. Using LocalDate and DateTimeFormatter
Alright here we define our date again and 2 DateTimeFormatter.
DateTimeFormatter oldFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
DateTimeFormatter newFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
The first formatter is our old date format, and the second one is the new one that we are gonna convert the old date into.
Alright lets use them now!
Now we make a new LocalDate object using our oldFormatter by parsing our dateString with the oldFormatter object
LocalDate dateTime = LocalDate.parse(date, oldFormatter);
Alright now lets format it.
String reformattedDate = dateTime.format(newFormatter);
as simple as that! Here is the full code.
String date = "11-12-2018";
DateTimeFormatter oldFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
DateTimeFormatter newFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate dateTime = LocalDate.parse(date, oldFormatter);
String reformattedDate = dateTime.format(newFormatter);
System.out.println(reformattedDate);
3. Using String::Split
Okay this part is pretty simple. Lets split the date using -
String[] dates = date.split("-");
We already know the order of the date lets format it using String::format
String reformattedDate = String.format("%s-%s-%s", dates[2], dates[1], dates[0]);
Here is the full code
String date = "11-12-2018";
String[] dates = date.split("-");
String reformattedDate = String.format("%s-%s-%s", dates[2], dates[1], dates[0]);
System.out.println(reformattedDate);
Try code below that will work for your case:
First parse your input format from string,
String date = "11-12-2018";
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
Then convert it to desired format,
Date dateTobeParse = null;
try {
dateTobeParse = df.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
if (dateTobeParse != null) {
SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd");
String outputDate = outFormat.format(dateTobeParse);
}
This is the common function which I use for date and time conversion
public String convertDateAndTime(String date, String oldFormat, String newFormat) {
SimpleDateFormat sdf = new SimpleDateFormat(oldFormat);
Date currentdate;
String converted = "";
try {
currentdate = sdf.parse(date);
SimpleDateFormat sdf2 = new SimpleDateFormat(newFormat);
converted = sdf2.format(currentdate);
} catch (ParseException e) {
e.printStackTrace();
}
return converted;
}
You just have to pass the date string and their old and new formats.
In your case call this function like this
String converteddate = convertDateAndTime("11-12-2018","dd-mm-yyyy","yyyy-MM-dd");
Try the code below that will work
1) Make method like below
public String changeDateFormat(String currentFormat, String requiredFormat, String dateString) {
String result = "";
SimpleDateFormat formatterOld = new SimpleDateFormat(currentFormat, Locale.getDefault());
SimpleDateFormat formatterNew = new SimpleDateFormat(requiredFormat, Locale.getDefault());
Date date = null;
try {
date = formatterOld.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
if (date != null) {
result = formatterNew.format(date);
}
return result;
}//end of changeDateFormat()
1st argument of the method is your current date format in your case it will be 'dd-MM-yyyy'
2nd argument is output or requires date format in your case it will be 'yyyy-MM-dd'
3rd argument is your date that you want to change the format
2) Run the method like below
String oldFormatDate = "11-12-2018";
String myDate = changeDateFormat("dd-MM-yyyy", "yyyy-MM-dd", oldFormatDate);
Log.d(TAG, "Old formatted Date : " + oldFormatDate);
Log.d(TAG, "New Date is : " + myDate);
3) Output:
Old formatted Date : 11-12-2018
New Date is : 2018-12-11
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"));
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);
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.
I am working on Java. I have a date for example: 20120328.
Year is 2012, month is 03 & day is 28.
I want to convert it into yyyy-MM-dd format.
I have tried it but it is not working.
How to do it?
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Date date = new Date();
String ourformat = formatter.format(date.getTime());
If you want other than "MM/dd/yyyy" then just change the format in SimpleDateFormat
Find some examples here.
DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
Date date = (Date)formatter.parse("01/29/02");
Take a look here. You will need to use the SimpleDateFormat class.
First you create the format using substring like
String myDate = "20120328";
String myConvertedDate = myDate.substring(0,4) + "-" + myDate.substring(5,6) + "-" + myDate.substring(7);
This produces the date as 2012-03-28
Then use simple date format to convert that into date if required.
You can use this one for Date formatting
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Date date = new Date();
String ourformat = formatter.format(date.getTime());
And this one for getting TimeStamp
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Timestamp timestamp =timestamp=new Timestamp(System.currentTimeMillis());
String ourformat = formatter.format(timestamp);