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 ""
}
}
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
I need to convert a time stamp that currently is in string format "08.00" to a valid time in java so I later can compare time. How do I convert this string to time?
Something like this
DateFormat sdf = new SimpleDateFormat("hh:mm");
Date date = sdf.parse(time);
Instead of using the Date and/or SimpleDateFormat classes, perhaps consider LocalTime
String time = "08:00";
LocalTime lt = LocalTime.parse(time);
System.out.println(lt);
Output:
08:00
And can compare to other times easily with LocalTime::isBefore() or LocalTime::isAfter()
Example
Try below code,
String time = "08.00";
try {
DateFormat sdfInput = new SimpleDateFormat("hh.mm");
Date date = sdfInput.parse(time);
DateFormat sdfOutput = new SimpleDateFormat("hh:mm");
Log.e( "Time: ", sdfOutput.format(date));
} catch (Exception e) {
e.printStackTrace();
}
Output -> Time: 08:00
The easiest way to do so is with a SimplDateFormatter:
DateFormat sdf = new SimpleDateFormat("hh:mm")
Then you can call Date date = sdf.parse(*your time string*)
Now you have your time as a valid Date object.
I have timeformat like this hhmmss="151918"
so you can use any format instead of hhmmss according to your current time format like
"hh.mm" or hh:mm:ss etc
and you can call this method form any where you needed.
fun convertTimeFormat(time:String):String{
var formattedTime=""
try {
val inputFormat: DateFormat = SimpleDateFormat("hhmmss")
val timeObj = inputFormat.parse(time)
Log.d("timeObj",""+timeObj)
formattedTime=SimpleDateFormat("hh:mm aa").format(timeObj)
} catch (e: ParseException) {
e.printStackTrace()
}
return formattedTime
}
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");
}
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);