how to change format of date from string date - java

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

Related

Change a Java date-time string to date

Well I tried to look for many questions but couldn't find something relevant. I have a string that has the following data:
String sDate = "2018-01-17 00:00:00";
This comes from an application, and I need to convert it into the following Date format
17-01-2018
I went through this link but could not relate.
Can someone help..?
If you are using Java 8, you can use java.time library and :
String sDate = "2018-01-17 00:00:00";
//Step one : convert the String to LocalDateTime
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime date = LocalDateTime.parse(sDate, formatter);
//Step two : format the result date to dd-MM-yyyy
String result = date.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));
Output
17-01-2018
Another Overengineering solution (It works just in your case) you can benefits from the default format of LocalDateTime :
String result = LocalDateTime.parse(sDate.replace(" ", "T"))
.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));
public static void main(String args[]) {
String sDate = "2018-01-17 00:00:00";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = df.parse(sDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SimpleDateFormat df1 = new SimpleDateFormat("dd-MM-yyyy");
System.out.println(df1.format(date));
}
it should solve your problem.
You need to use the SimpleDateFormat:
String sDate = "2018-01-17 00:00:00";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = df.parse(sDate);
SimpleDateFormat df1 = new SimpleDateFormat("dd-MM-yyyy");
System.out.println(df1.format(date));
Go through the SimpleDateFormat class to get into details for this

Converting of string type to date parse not working

I am converting the string type to date and parsing it to a HH:mm format but while formatting its not working throwing exception,campusconfig.getworktime() is date Below is my code
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
if ((from1 != null)) {
if(campusConfig.getWorkFromTime()!=null){
String time = "";
Date timech;
time = campusConfig.getWorkFromTime().toString();
timech = dateFormat.parse(time);
if(from1.before(timech)){
String errormsg = message.getString("message.reports.time.select.campustime");
errorMessageUI(errormsg);
}
If campusConfig contains a full date (date and time) you need to parse it with SimpleDateFormat ("yyyy-MM-dd HH:mm:ss.SSSSSS") (with the correct format) then you can trasform the date in only time with other SimpleDateFormat("HH:mm") format(date).
Sample:
public class DateFormat {
public static void main(String[] args) throws ParseException {
String campusConfig = "2015-11-26 11:46:20";
SimpleDateFormat sdf_in = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d = sdf_in.parse(campusConfig);
SimpleDateFormat sdf_out = new SimpleDateFormat("HH:mm");
System.out.println("Only Time : " + sdf_out.format(d));
}
}
try something like below,
new SimpleDateFormat("HH:mm").format(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(campusConfig.getWorkFromTime().toString()));
try this
java.util.Date temp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS").parse("2012-07-10 14:58:00.000000");

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

How to convert String of datetime to date using GWT?

In mysql, i have a field time_entered of type datetime (sample data: 2012-06-20 16:00:47). I also have a method, getTimeEntered(), that returns the value as String. I want to display the date in this format 2012-06-20 using DateTimeFormat from GWT.
here's my code:
String date = aprHeaderDW.getTimeEntered();
DateTimeFormat fmt = DateTimeFormat.getFormat("MM-dd-yyyy");
dateEntered.setText("" + fmt.format(date));
The problem is, the format method doesn't accept arguments as String. So if there's only a way I could convert the date from String to Date type, it could probably work. I tried typecasting but didn't work.
You should be able to just use DateTimeFormat.
Date date = DateTimeFormat.getFormat("yyyy-MM-dd HH:mm:ss").parse("2012-06-20 16:00:47");
String dateString = DateTimeFormat.getFormat("yyyy-MM-dd").format(date);
Otherwise there is a light-weight version of SimpleDateFormat that supports this pattern.
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2012-06-20 16:00:47");
Hi There are two options.
The first is as it is already a string you could use a regular expression to modify the format.
The second is using a SimpleDateFormater you can parse the string to a date then back again.
For example:
public class DateMerge {
public static void main(String arg[])
{
String out = dateConvert("2012-06-20 16:00:47");
System.out.println(out);
}
public static String dateConvert (String inDate)
{
try {
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
date = (Date)formatter.parse(inDate);
formatter = new SimpleDateFormat("dd-MM-yyyy");
String outDate = formatter.format(date);
return outDate;
} catch (ParseException e)
{System.out.println("Exception :"+e); }
return null;
}
}
You may use like this.
String date = "2012-06-20 16:00:47";
SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
String lDate=sf.format(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date));
System.out.println(lDate);
Output:
2012-06-20
After trying a lot of times I came up with a solution, based on #Keppil and adding my own code.
Here's Keppil's suggested solution for converting String datetime into Date type:
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2012-06-20 16:00:47");
...but my second requirement is to display just the date like 2012-06-20. Even though I removed HH:mm:ss, it still displayed the time like this 2012-06-20 00:00:00.
Here's my final solution:
Date date = null;
String d = rs.getString(SQL_CREATION_TIME); // assigns datetime value from mysql
// parse String datetime to Date
try {
date = new SimpleDateFormat("yyyy-MM-dd").parse(d);
System.out.println("time entered: "+ date);
} catch (ParseException e) { e.printStackTrace(); }
// format the Date object then assigns to String
Format formatter;
formatter = new SimpleDateFormat("yyyy-MM-dd");
String s = formatter.format(date);

Convert string to date format in android

I'm trying to convert string to date format.I trying lot of ways to do that.But not successful. my string is "Jan 17, 2012". I want to convert this as " 2011-10-17".
Could someone please tell me the way to do this? If you have any worked through examples, that would be a real help!
try {
String strDate = "Jan 17, 2012";
//current date format
SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy");
Date objDate = dateFormat.parse(strDate);
//Expected date format
SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
String finalDate = dateFormat2.format(objDate);
Log.d("Date Format:", "Final Date:"+finalDate)
} catch (Exception e) {
e.printStackTrace();
}
String format = "yyyy-MM-dd";
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
Which produces this output when run in the PDT time zone:
yyyy-MM-dd 1969-12-31
yyyy-MM-dd 1970-01-01
For more info look at here
I suggest using Joda Time, it's the best and simplest library for date / dateTime manipulations in Java, and it's ThreadSafe (as opposed to the default formatting classes in Java).
You use it this way:
// Define formatters:
DateTimeFormatter inputFormat = DateTimeFormat.forPattern("MMM dd, yyyy");
DateTimeFormatter outputFormat = DateTimeFormat.forPattern("yyyy-MM-dd");
// Do your conversion:
String inputDate = "Jan 17, 2012";
DateTime date = inputFormat.parseDateTime(inputDate);
String outputDate = outputFormat.print(date);
// or:
String outputDate = date.toString(outputFormat);
// or:
String outputDate = date.toString("yyyy-MM-dd");
// Result: 2012-01-17
It also provides plenty of useful methods for operations on dates (add day, time difference, etc.). And it provides interfaces to most of the classes for easy testability and dependency injection.
Why do you want to convert string to string try to convert current time in milisecond to formated String,
this method will convert your milisconds to a data formate.
public static String getTime(long milliseconds)
{
return DateFormat.format("MMM dd, yyyy", milliseconds).toString();
}
you can also try DATE FORMATE class for better understanding.
You can't convert date from one format to other. while you are taking the date take you have take the date which ever format the you want. If you want the date in yyyy-mm-dd. You can get this by using following way.
java.util.Calendar calc = java.util.Calendar.getInstance();
int day = calc.get(java.util.Calendar.DATE);
int month = calc.get(java.util.Calendar.MONTH)+1;
int year = calc.get(java.util.Calendar.YEAR);
String currentdate = year +"/"+month +"/"+day ;
public static Date getDateFromString(String date) {
Date dt = null;
if (date != null) {
for (String sdf : supportedDateFormats) {
try {
dt = new Date(new SimpleDateFormat(sdf).parse(date).getTime());
break;
} catch (ParseException pe) {
pe.printStackTrace();
}
}
}
return dt;
}
Try this simple method:
fun getFormattedDate(strDate:String): String {
try {
val dateFormat = SimpleDateFormat("dd/mm/yyyy")//old format
val dateFormat2 = SimpleDateFormat("mm/dd/yyyy")//require new formate
val objDate = dateFormat.parse(strDate)
return dateFormat2.format(objDate)
} catch (e:Exception) {
return ""
}
}

Categories