How to format date/time string? (Java) - java

Hi can anyone help please? I am trying to format a date and time string.
Currently it looks like this "20160112T110000Z" and I need it to be "2016-01-12T11:00:00Z"
The string without the special characters are returned from a 3rd party recurrence library. I need to convert it to have the special characters before parsing it to a Calendar object.
Can anyone help please?
The code that I have so far looks like:
final String TIMEFORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
String string = "20160112T110000Z";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Date date = format.parse(string);
System.out.println(date);
However this just does not work.
Any suggestions are appreciated

You have to read the string with a format matching the source, this gives you a correct Date.
Then simply write it with the format you want :
String string = "20160112T110000Z";
String originalStringFormat = "yyyyMMdd'T'HHmmss'Z'";
String desiredStringFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'";
SimpleDateFormat readingFormat = new SimpleDateFormat(originalStringFormat);
SimpleDateFormat outputFormat = new SimpleDateFormat(desiredStringFormat);
try {
Date date = readingFormat.parse(string);
System.out.println(outputFormat.format(date));
} catch (ParseException e) {
e.printStackTrace();
}

try this
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
// you can change format of date
Date date = formatter.parse(strDate);
Timestamp timeStampDate = new Timestamp(date.getTime());
return timeStampDate;

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

How to converted timestamp string to a date in java

I have a string "1427241600000" and I want it converted to "yyyy-MM-dd" format.
I have tried, but I am not able to parse it, please review the below code
try {
String str = "1427241600000";
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
Date date =sf.parse(str);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
I would like to know where I went wrong.
You should try it the other way around. First get the Date out of the milliTime and then format it.
String str = "1427241600000";
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date(Long.parseLong(str));
System.out.println(sf.format(date));
the conversion is highly dependent on what format the timestamp is in. But i assume the whole thing should actually be a long and is simply the systemtime from when the timestamp was created. So this should work:
String str = ...;
Date date = new Date(Long.parseLong(str));
Use Date date =new Date(Long.parseLong(str)); to convert your String to Date object.
if you are using SimpleDateFormat() the format specified as a parameter to this function should match the format of the date in the String (str in your case). In your case yyyy-MM-dd does not match the format of the time stamp (1427241600000).
You can do it like this:
use a SimpleDateFormat with an appropriate format string (be careful to use the correct format letters, uppercase and lowercase have different meanings!).
DateFormat format = new SimpleDateFormat("MMddyyHHmmss");
Date date = format.parse("022310141505");

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

String to Date in Java

HI,
I am converting String to Date format. But it returns wrong dates. for example,
String startDate = "08-05-2010"; // (MM/dd/yyyy)
I want to convert this to "Date" object like this, 05-JUL-10
How to do that? I tried like this
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yy");
scal1.setTime(dateFormat.parse((startDate)));
but i am getting "Unparseable date:" .
If you want to convert a date string of one format to another format, you can use format() and parse() methods of SimpleDateFormat class
First you need to parse the string to a date object using parse() method setting the source pattern and then format the date object using format() method setting the target pattern:
SimpleDateFormat sourceFormat = new SimpleDateFormat("MM-dd-yyyy");
Date sourceFormatDate = sourceFormat.parse("08-05-2010");
SimpleDateFormat destFormat = new SimpleDateFormat("dd-MMM-yy");
String destFormatDateString = destFormat.format(sourceFormatDate);
System.out.println(destFormatDateString); // 05-Aug-10
Unless you've left something out, it looks like you're trying to parse it with the wrong format, i.e. you have an mm-dd-yyyy, and you're trying to parse it with the format dd-MMM-yy. Try a separate date format for what you're parsing from what you're encoding.
SimpleDateFormat format = new SimpleDateFormat(“yyyy-MM-dd”);
String strDate = “2007-12-25″;
Date date = null;
try {
date = format.parse(strDate);
} catch (ParseException ex) {
ex.printStackTrace();
}
The format dd-MMM-yy you use to parse the string is wrong; the format should be dd-MM-yyyy.
String startDate = "08-05-2010";
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = dateFormat.parse((startDate));
Note that Date objects themselves do not have a format: a Date objects just represents a date and time value, just like an int is just a number, and doesn't have any inherent formatting information. If you want to display the Date in a certain format, you'll have to use a DateFormat object again to format it:
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yy");
System.out.println(dateFormat.format(date));
// output: 08-May-10

How to convert time data in java?

The following time formats are in outlook calendar file
DTSTART;TZID="Eastern":20100728T140000
DTEND;TZID="Eastern":20100728T150000
how to convert this time to java time format.
This looks like iCalendar. Take a look at ical4j - a Java API for it.
Without tested, look at SimpleDateFormat
String ds = "DTSTART;TZID=\"Eastern\":20100728T140000";
Date d = new SimpleDateFormat("yyyyMMdd'T'HHMMSS").parse(ds.split(":")[1]);
Handling the timezone will be tricky as "Eastern" is not an actual timezone. However if you handle that, I would suggest the following SimpleDateFormat will handle the unadjusted parse for you.
Date unadjusted =
new SimpleDateFormat("yyyyMMdd'T'HHmmss").parse(line.split(":")[1]);
Another way using always SimpleDateFormat:
String[] strings = new String[]{"DTSTART;TZID=\"Eastern\":20100728T140000", "DTEND;TZID=\"Eastern\":20100728T150000"};
for (String string : strings) {
String dateString = string.replaceAll("(DTSTART|DTEND);TZID=\"Eastern\":", "");
dateString = dateString.replaceAll("T", "");
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
try {
Date date = sdf.parse(dateString);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
}

Categories