This question already has answers here:
Java date format conversion - getting wrong month
(8 answers)
How to parse a date? [duplicate]
(5 answers)
Closed 5 years ago.
My method is :
public String changeCurrentDate(Integer variant){
String currentTime = TestApp.getInstance().getDriver().findElement(By.id("common.HeaderComponent.mainLayout.serverTimeLabel")).getText();
String currentDate = currentTime.substring(0, 10);
System.out.println("currentDate " +currentDate);
String date = null;
DateFormat df = new SimpleDateFormat("dd/mm/yyyy");
try{
Date date3 = df.parse(currentDate);
df.format(date3);
System.out.println("date3 " +date3);
Date previousDate = DateUtils.addDays(date3, variant);
date = previousDate.toString();
return date;
}catch (Exception e){
}
return date;
}
Note : currentTime variable always have the value like "18/12/2017"
I'm expecting result of date in dd/mm/yyyy format. but it always gives "Wed Jan 18 00:12:00 IST 2017" like this.
Run Time Results :
currentDate 18/12/2017
date3 Wed Jan 18 00:12:00 IST 2017
You should return the formatted date, not the toString() of the date. Try this:
Date previousDate = DateUtils.addDays(date3, variant);
return df.format(previousDate);
df.format simply returns a String representation of the Date with the format applied, therefore the line you have in your code has no effect.
Try changing you code to use the formatted output instead:
public String changeCurrentDate(Integer variant){
String currentTime = TestApp.getInstance().getDriver().findElement(By.id("common.HeaderComponent.mainLayout.serverTimeLabel")).getText();
String currentDate = currentTime.substring(0, 10);
System.out.println("currentDate " +currentDate);
DateFormat df = new SimpleDateFormat("dd/mm/yyyy");
Date date3 = df.parse(currentDate);
System.out.println("date3 " + df.format(date3));
Date previousDate = DateUtils.addDays(date3, variant);
return previousDate.toString();
}
Also - its bad to catch Exception, so you should remove that.
We should always try to find out the more convenient way so that we can further use it. In that case, we can use below method:
public String dateString(String input) {
SimpleDateFormat parser = new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
String formattedDate = "";
try {
Date date = parser.parse(input);
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
formattedDate = formatter.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return formattedDate;
}
You can easily call this method like below:
Date date3 = df.parse(currentDate);
df.format(date3);
String input = date3.toString();
String requiredDate = dateString(input);
System.out.println("requiredDate: "+ requiredDate);
Which returns the output like below:
requiredDate: 18/12/2017
Related
I have String with date format dd.MM.yyyy, and I want to upload it to my MS SQL server, but the required format is yyyy-MM-dd. I tried this but it doesn't work like I want to.
String expDate = mDatePickerBtn.getText().toString();
Date date = null;
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
try {
date = format.parse(expDate);
expDate = date.getYear() + "-" + date.getMonth() + "-" + date.getDay();
} catch (ParseException e) {
e.printStackTrace();
}
For example if I pass 31.12.2032 to the expDate, the date variable will cointain "Fri Dec 31 00:00:00: GMT+01:00 2032", and the expDate will contain "132-11-5" and I don't even know why.
I would use DateTimeFormatter but my minimal API level is 24.
My question is: where did I make mistake or how else can I get correct format out of this?
Go compile your app with Android Gradle Plugin 4.0.0+ and use java.time then like this:
public static void main(String[] args) {
// get / provide the String to be parsed
String expDate = "31.12.2032";
// provide a pattern that parses such a date
String pattern = "dd.MM.uuuu";
// create a DateTimeFormatter with this pattern
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
// parse the String with the DateTimeFormatter
LocalDate expLocalDate = LocalDate.parse(expDate, dtf);
// print the default format of a LocalDate
System.out.println(expLocalDate);
// print the LocalDate using the pattern created for parsing
System.out.println(expLocalDate.format(dtf));
// create a totally different DateTimeFormatter inline and format the date differently
System.out.println(expLocalDate.format(DateTimeFormatter.ofPattern("EEE, dd 'of' MMMM uuuu",
Locale.ENGLISH)));
}
The output would be this:
2032-12-31
31.12.2032
Fri, 31 of December 2032
Try this way
String expDate = mDatePickerBtn.getText().toString();
Date date = null;
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
try {
date = format.parse(expDate);
SimpleDateFormat format1 = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
format1.format(date);
expDate = format1.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
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
This question already has answers here:
Y returns 2012 while y returns 2011 in SimpleDateFormat
(5 answers)
Closed 5 years ago.
I am trying to parse string into a date using the following code:
public static Date dateFormatter(String s)
{
SimpleDateFormat ft = new SimpleDateFormat ("MMddYYYY");
Date excelDate=null;
try
{
excelDate = ft.parse(s);
Date formatString = ft.format(excelDate);
System.out.println("Date to be printed in Excel is :" +formatString);
return excelDate;
}
catch(Exception ae)
{
System.out.println("No date");
}
return excelDate;
}
I am passing in the argument "04202017".
This function is not working for me. I am not able to figure out what I am doing wrong. Can anybody please help me?
You have to use ft.parse(s); instead of format(excelDate). Format is the other way (Date -> String)
DateFormat.parse(String)
And you dont have to parse the Date back to a String.
Corrected code:
public static Date dateFormatter(String s) {
SimpleDateFormat ft = new SimpleDateFormat ("MMddYYYY");
Date excelDate = null;
try {
excelDate = ft.parse(s);
System.out.println("Date to be printed in Excel is :" +excelDate);
return excelDate;
} catch(Exception ae) {
System.out.println("No date");
}
return excelDate;
}
You already parsed String s to excelDate with date format that you want. So i think it's good and enough to print just excelDate.
System.out.println("Date to be printed in Excel is :" +excelDate);
Like that.
And also change MMddYYYY to MMddyyyy.
Try parse method instead of format
For String to Date, use:
SimpleDateFormat.parse(String);
For Date to String, use:
SimpleDateFormat.format(date);
However, in your code, you already parsed the String and assigned into excelDate on this line:
excelDate = ft.parse(s);
try this one:
String string = "march 9, 2017";
DateFormat format = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
Date date = format.parse(string);
System.out.println(date);
It would be nice to use Java 1.8's new time classes (which are in java.time.* package).
public static void main(String[] args)
{
LocalDateTime dateTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// To String
String dateString = dateTime.format(formatter);
System.out.println(dateString);
// To LocalDateTime
LocalDateTime parsedLocalDateTime = LocalDateTime.parse(dateString, formatter);
}
This question already has answers here:
java date format yyyy-mm-dd.hh.MM.ss.ms
(3 answers)
Closed 7 years ago.
I have a date string which is as follows:
2015-12-24 08:06:44
Now I have a parse function:
public static String parseDate(String date) {
Date oldDate = null;
try {
System.out.println("Unparsed: "+date);
DateFormat oldFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
oldDate = oldFormat.parse(date);
System.out.println("old Date parsed: "+oldDate);
DateFormat newFormat = new SimpleDateFormat("yyyy-mm-dd", Locale.ENGLISH);
Date result = newFormat.parse(oldDate.toString());
return result.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
The first System.out gives me:
Unparsed: 2015-12-24 08:06:44
The second one:
Sat Jan 24 08:06:44 GMT+05:30 2015
Whereas for the second one I have clearly mentioned the date format to be as:
new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
Please advise on what's wrong here
I only want to get the month and day from the input string - Desired would be Dec 24 from the above sample date string.
Its MM for month not mm.
DateFormat oldFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
SimpleDateFormat doc
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 ""
}
}