Date convert in Java - 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.

Related

how to change format of date from string date

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

Compare two dates with time whose Formate is yyyy-MM-dd HH:mm:ss in Android

I have to compare two dates whose format is yyyy-MM-dd HH:mm:ss. I know the way to compare date only the before or after date function.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDateandTime = sdf.format(new Date());
String expiryTime = "2014-09-10 00:00:00";
But what's the best way to compare date and time with the current date and time.
Like we have two dates 2014-09-10 00:00:00 and current date with time is 2014-08-31 10:37:15. And now we have to compare it. How we can do that.
Any help is appreciated.
Convert the Date String to java.util.Date object using SimpleDateFormat and compare those date objects with Date#after or Date#before methods.
In java 8 - using new Java Time API, parse date String using DateTimeFormat and get LocalDate object and compare them.
DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
final LocalDate dt1 = dtf.parseLocalDate(dateString1);
final LocalDate dt2 = dtf.parseLocalDate(dateString2);
final boolean check = dt1.isAfter(dt2);
if(check)
System.out.println(dt1 +" is after "+dt2);
else
System.out.println(dt2 +" is after "+dt1);
If I understand what you're trying to do you want to use a SimpleDateFormat (and you posted a good pattern) to parse the String(s) into Date(s) and then Date.before(Date). Putting that together into something like,
DateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
String firstStr = "2014-09-10 00:00:00";
String secondStr = "2014-08-31 10:37:15";
Date first = sdf.parse(firstStr);
Date second = sdf.parse(secondStr);
boolean before = (first.before(second));
System.out.printf("%s is before %s",
before ? firstStr : secondStr,
before ? secondStr : firstStr);
Output is
2014-08-31 10:37:15 is before 2014-09-10 00:00:00
try{
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
} catch (ParseException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
String str1 = "2014-09-10 00:00:00";
Date date1 = formatter.parse(str1);
String str2 = "2014-08-31 10:37:15";
Date date2 = formatter.parse(str2);
if (date1.compareTo(date2)<0)
{
System.out.println("date2 is Greater than my date1");
}

Convert date into specific format

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);

How to get Date format like this in android?

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;
}

Java ParseException while attempting String to Date parsing

I'm having a hard time Parsing/Formatting a Date string received back from a web service. I've attempted multiple approaches, but with no luck.
Sample Date String:
2011-10-05T03:00:00Z
Exception:
W/System.err(10072): java.text.ParseException: Unparseable date: "2011-10-05T05:00:00Z" (at offset 10)
W/System.err(10072): at java.text.DateFormat.parse(DateFormat.java:626)
Sample Code:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:SSSS");
Date date = formatter.parse(info.AiringTime);
I've found that if I remove the "T" between the date and the time and replace it with a space, it will format just fine. Anybody have any suggestions?
--UPDATE--
After looking deeper into the API documentation, I found this:
All response DateTime values are in UTC format. You need to apply the UTC offset to calculate the local time for display.
DateTime is a date-and-time value specified in one of the following formats:
UTC format: YYYY-MM-DDThh:mm:ssZ. For example: 2011-03-15T02:00:00Z.
Local time with an offset: YYYY-MM-DDThh:mm:ss + or - hh:mm (positive or negative offset). For example, for US Pacific time: 2011-03-14T06:00:00 -08:00.
Any suggestions on the UTC format approach?
You could try:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
String dateString = dateString.replace("Z", "GMT+00:00");
Date date = dateFormat.parse(dateString);
The above code should correctly handle the case where a timezone is specified in the date. As Z represents the UTC/GMT timezone it is replaced by GMT so the SimpleDateFormat can interpret it correctly (i would love to know a cleaner way of handling this bit if anyone knows one).
Try,
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
This pattern should parse the date you provide: "yyyy-MM-dd'T'HH:mm:ss'Z'".
If you want to use SimpleDateFormat and you have a limited number of variations, you can create separate formatters for each pattern and chain them:
Date date = formatter1.parse(info.AiringTime);
if (date == null)
{
date = formatter2.parse(info.AiringTime);
if (date == null)
{
date = formatter2.parse(info.AiringTime);
if (date == null)
{
date = formatter3.parse(info.AiringTime);
}
}
}
or put them in a list and iterate until non-null or no more formatters.
If you have too many patterns for this to be practical, you can parse it yourself or try one of these libraries.
This worked for me
SimpleDateFormat isoDateFormat = new SimpleDateFormat("yyyy-mm-dd'T'hh:mm:ss'Z'");
SimpleDateFormat viewFriendlyDateFormat = new SimpleDateFormat("dd/MMM/yyyy hh:mm:ss aaa");
String viewFriendlyDate = "";
try {
Date date = isoDateFormat.parse(timestamp);
viewFriendlyDate = viewFriendlyDateFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat isoDateFormat = new SimpleDateFormat("yyyy-mm-dd'T'hh:mm:ss'Z'");
SimpleDateFormat viewFriendlyDateFormat = new SimpleDateFormat("dd/MMM/yyyy hh:mm:ss aaa");
String viewFriendlyDate = "";
try {
Date date = isoDateFormat.parse(timestamp);
viewFriendlyDate = viewFriendlyDateFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}

Categories