Encountering issue in SimpleDateFormat parse method in Java - java

I am trying to use SimpleDateFormat.parse method to parse a date string to Date object, but it is omitting "T" in the final date that is returned. I am passing this date string 2015-04-15T12:55:07.365 and I am getting 2015-04-15 12:55:07.365 in the output. However, the desired output is 2015-04-15T12:55:07.365.
Why is "T" in the final output omitted by this line parsedDate = sdf.parse(transDate);
public static void main(String[] args)
{
try
{
final String pattern = "yyyy-MM-dd'T'hh:mm:ss.SSS"; // example 2015-04-15T12:55:07.365
final SimpleDateFormat sdf = new SimpleDateFormat(pattern);
String transDate = "2015-04-15T12:55:07.365";
Date parsedDate = sdf.parse(transDate);
System.out.println("transDate:"+transDate+", parsedDate: "+parsedDate);
}

You never get your desired output 2015-04-15T12:55:07.365
Why?
Because you are printing Date object parsedDate.Date class has it's own toString() method implementation.When you are printing the date object, it means it basically prints the toString() method implementation format.
see the Java doc for details

System.out.println(parsedDate) would give you Wed Apr 15 00:55:07 GMT 2015 which is the toString() representation of the date object.
You can use SimpleDateFormat to parse AND format dates:
SimpleDateFormat sdfParser = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS");
Date date = sdfParser.parse("2015-04-15T12:55:07.365");
SimpleDateFormat sdfFormatter = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS");
String formattedDate = sdfFormatter.format(date);
System.out.println(formattedDate);
// 2015-04-15T12:55:07.365

You will get desired output here.
public static void main(String args[]) {
{
try {
String transDate = "2015-04-15T12:55:07.365";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS");
Date date = sdf.parse(transDate);
SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date d = sdf.parse(sdf.format(date));
String formattedTime = output.format(d);
System.out.println("transDate:" + transDate + ", parsedDate: " + formattedTime);
} catch (Exception e) {
}
}
}

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

Remove the hour,minute and seconds from date gotten from server as JSON

I am getting some JSON data from server that includes dates too. But it shows the date like this 2017-07-20 00:00:00 but I want to just see the date like this:2017-07-20, and i checked the previous questions about this issue but all of them were based on the date in the android side. And the problem is that I get the date as JSON and because of that I don't know how to remove Time from it.
Did you try to simple parse this string like this?
String date_string = "2017-07-20 00:00:00";
String[] parsed = date_string.split(" ");
String your_wanted_string = parsed[0];
System.out.println(your_wanted_string);
EDIT
You have to convert string into Date like here : https://stackoverflow.com/a/4216767/1979882
Convert Date to milliseconds. Or use Calendar class.
Calculate the difference between the values.
An example:
http://www.mkyong.com/java/how-do-get-time-in-milliseconds-in-java/
public class TimeMilisecond {
public static void main(String[] argv) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
String dateInString = "22-01-2015 10:20:56";
Date date = sdf.parse(dateInString);
System.out.println(dateInString);
System.out.println("Date - Time in milliseconds : " + date.getTime());
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
System.out.println("Calender - Time in milliseconds : " + calendar.getTimeInMillis());
}
}
String date_from_json="your date goes here";
parseDate(date_from_json);
public String parseDate(String s) {
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-mm-dd");
Date date = null;
String str = null;
try {
date = inputFormat.parse(s);
str = outputFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return str;
}
You can use my javascript function to do this task from client side:
function formatDate(dateString) {
var date = new Date("2017-07-20 00:00:00"),
dd = date.getDate(),
mm = date.getMonth() + 1,
yyyy = date.getFullYear();
mm = mm < 10 ? '0' + mm : mm;
return dd + '-' + mm +'-' + yyyy;
}
call:
var dateStr = formatDate("2017-07-20 00:00:00");
demo

Parsing String into date using java [duplicate]

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

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

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

Categories