Converting date-string to a different format - java

I have a string containing a date in the format YYYY-MM-DD.
How would you suggest I go about converting it to the format DD-MM-YYYY in the best possible way?
This is how I would do it naively:
import java.util.*;
public class test {
public static void main(String[] args) {
String date = (String) args[0];
System.out.println(date); //outputs: YYYY-MM-DD
System.out.println(doConvert(date)); //outputs: DD-MM-YYYY
}
public static String doConvert(String d) {
String dateRev = "";
String[] dateArr = d.split("-");
for(int i=dateArr.length-1 ; i>=0 ; i--) {
if(i!=dateArr.length-1)
dateRev += "-";
dateRev += dateArr[i];
}
return dateRev;
}
}
But are there any other, more elegant AND effective way of doing it? Ie. using some built-in feature? I have not been able to find one, while quickly searching the API.
Anyone here know an alternative way?

Use java.util.DateFormat:
DateFormat fromFormat = new SimpleDateFormat("yyyy-MM-dd");
fromFormat.setLenient(false);
DateFormat toFormat = new SimpleDateFormat("dd-MM-yyyy");
toFormat.setLenient(false);
String dateStr = "2011-07-09";
Date date = fromFormat.parse(dateStr);
System.out.println(toFormat.format(date));

Here’s the modern answer.
private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-uuuu");
public static String doConvert(String d) {
return LocalDate.parse(d).format(formatter);
}
With this we may do for example:
System.out.println(doConvert("2017-06-30"));
This prints
30-06-2017
I am exploiting the fact that the format you have, YYYY-MM-DD, conforms with the ISO 8601 standard, a standard that the modern Java date and time classes “understand” natively, so we need no explicit formatter for parsing, only one for formatting.
When this question was asked in 2011, SimpleDateFormat was also the answer I would have given. The newer date and time API came out with Java 8 early in 2014 and has also been backported to Java 6 and 7 in the ThreeTen-Backport project. For Android, see the ThreeTenABP project. So these days honestly I see no excuse for still using SimpleDateFormat and Date. The newer classes are much more programmer friendly and nice to work with.

Best to use a SimpleDateFormat (API) object to convert the String to a Date object. You can then convert via another SimpleDateFormat object to whatever String representation you wish giving you tremendous flexibility.

If you're not looking for String to Date conversion and vice-versa, and thus don't need to handle invalid dates or anything, String manipulation is the easiest and most efficient way. But i's much less readable and maintainable than using DateFormat.
String dateInNewFormat = dateInOldFormat.substring(8)
+ dateInOldFormat.substring(4, 8)
+ dateInOldFormat.substring(0, 4)

import java.util.DateFormat;
// Convert String Date To Another String Date
public String convertStringDateToAnotherStringDate(String stringdate, String stringdateformat, String returndateformat){
try {
Date date = new SimpleDateFormat(stringdateformat).parse(stringdate);
String returndate = new SimpleDateFormat(returndateformat).format(date);
return returndate;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
//-------
String resultDate = convertStringDateToAnotherStringDate("1997-01-20", "yyyy-MM-dd", "MM/dd/yyyy")
System.out.println(resultDate);
Result (date string) : 01/20/1997

Related

Convert a query’s date return with SimpleDateFormat

I'm trying to convert a resultset from ddMMyyyy HH:mm:ss (ex: 19/06/2022 00:00:10) to yyyyMMddHHmmss (should be 20220619000010) with SimpleDateFormate without success. This is how I'm doing:
I have an Util class, which has the follow class:
public class Utils {
public static String Format(String formato, Date date) {
date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String dataString = sdf.format(date);
return dataString;
}
}
And I also have a ResultSet class witch return the objects of my query based in another class. Example:
Class one:
public class MyFile {
String Date = new String ();
+ getter and setter
}
Class 2 (create the line of my document):
public static MyFile createRow (ResultSet rs) throws SQLException {
MyFile mf = new MyFile();
mf.setDate(Utils.Format(rs.getString("Date");
return mf;
}
The point is: This conversion doesn't work and I can't find another way to do this. Someone could help me, please?
The java message:
"The method Format(String, Date) in te type Utils is not applicable for the arguments (String)
3 quick fixes available:
+ add argument to match 'Format(String, Date)'
- Change method 'Format(String, Date)': Remove parameter 'Date'
º Create method 'Format(String) in type 'Utils'"
For the conversion, you'll need two SimpleDateFormats; one for parsing the string to date, another to turn the date to the desired format:
public static String Format(String formato, Date date) {
SimpleDateFormat inputFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
try {
date = new inputFormat.parse(formato);
} catch (ParseException ex) {
// wrong format?
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String dataString = sdf.format(date);
return dataString;
}
// usage
mf.setDate(Utils.Format(rs.getString("Date"), new Date()));
I presume your date parameter would be a default Date in case the formato input string is invalid.
If you want to do it with the packages java.time and java.time.format you can try something like this. Of course java.util.Date is stored essentially as milliseconds from the epoch without time zone, hence using UTC below. If you want the output to correspond to a particular time zone, then change it:
public static String formatDate(Date d) {
String result = null;
Instant i = Instant.ofEpochMilli(d.getTime());
ZonedDateTime zdt = ZonedDateTime.ofInstant(i, ZoneId.of("UTC"));
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
result = fmt.format(zdt);
return result;
}
First of all, I want to tell you that there are newer and more convenient libraries than the old java.util.Date library. I am not so experienced with the new ones, but mostly java.util.time (like here: Understanding Java util Date) or joda.time are recommended.
So maybe you want to consider using one of the newer library instead of the old SimpleDateFormat from java.util.Date, if you only just began coding with Dates and just picked the first library coming to your mind, I think it could be a good idea.
To your specific problem: The java error message just tells you how it is, in your utils class you have your String Format with the constructor with two input params, a String and a date. In this line:
mf.setDate(Utils.Format(rs.getString("Date");
you are calling your Utils.Format String, but you are only passing one argument, "rs.getString("Date")". So either you refactor your String Format Constructor to only take a string as an argument or you pass (like recommended in the java message) a string and a date, for instance like:
mf.setDate(Utils.Format(rs.getString("Date"), new Date();
While I'm writing this, I think in this line two closing brackets are missing. You should add them.
But I think it should not be that complicated to convert a String like 19/06/2022 00:00:10 into another format using SimpleDateFormat. All you need to do is
String sDate1="19/06/2022 00:00:10";
SimpleDateFormat formatter1=new SimpleDateFormat("yyyyMMddHHmmss");
Date date1=formatter1.parse(sDate1);
This way, in date1 should be your DateString in the Format you specified when initialising your SimpleDateFormat formatter1.
Here is the official doc to SimpleDateFormat: https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Thnx for your answers, but I couldn't make any work.
So, I tried another way with success. It is:
public static String Format (String date) {
String formattedDate= date.substring(0, 4)
+ date.substring(5, 7)
+ date.substring(8, 10)
+ date.substring(11, 13)
+ date.substring(14, 16)
+ date.substring(17, 19);
return formattedDate;
}
mf.setDate(Utils.Format(rs.getString("Date");

Convert String to Date and remove day value (always set 1 day of month) [duplicate]

This question already has answers here:
Get first date of current month in java
(11 answers)
Closed 4 years ago.
I can convert a String to a Date:
private static final SimpleDateFormat CARD_DATE_FORMAT = new SimpleDateFormat("yyMMdd", Locale.getDefault());
public static Date toCardDateFormat(String date){
try {
return CARD_DATE_FORMAT.parse(date);
} catch (ParseException e) {
return null;
}
}
For example I have 200908 - it will convert to 2020-09-08, but I need set the day always to 1st day of month. I need 2020-09-01. How can I make this?
According to your need,you can use this method:
private static final SimpleDateFormat CARD_DATE_FORMAT = new SimpleDateFormat("yyMMdd", Locale.getDefault());
public static String toCardDateFormat(String date) {
try {
Date value = CARD_DATE_FORMAT.parse(date);
SimpleDateFormat dateFormatter = new SimpleDateFormat("yy-MM", Locale.getDefault());
String datetimeLocale = dateFormatter.format(value);
String newDate = datetimeLocale + "-01";
return newDate;
} catch (ParseException e) {
return null;
}
}
for date object you can use this:
public static Date toCardDateFormat(String date) {
try {
Date value = CARD_DATE_FORMAT.parse(date);
SimpleDateFormat dateFormatter = new SimpleDateFormat("yy-MM", Locale.getDefault());
String datetimeLocale = dateFormatter.format(value);
String newDate = datetimeLocale + "-01";
SimpleDateFormat dateFormat = new SimpleDateFormat("yy-MM-dd",Locale.getDefault());
Date d = dateFormat.parse(newDate);
return d;
} catch (ParseException e) {
return null;
}
}
Maciej's answer is correct, but if you use Java 8 or higher, it's better to use the java.time classes:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyMMdd");
// parse and change the day of month
LocalDate d = LocalDate.parse("200908", formatter).withDayOfMonth(1);
System.out.println(d); // 2020-09-01
Note that the LocalDate is printed in the format you want - which is ISO8601 compliant. If you want a different format, just use another DateTimeFormatter and call the format method.
Manually changing the string, as suggested by others, might also work, but if you're dealing with dates, why not use a proper date-handling API? Direct string manipulation won't help you in cases like invalid dates (the formatter will throw an exception for invalid inputs), or if you try to change the day to invalid values (such as day 31 for April, or 29 for February in a non-leap year, which are checked by the API and throw an exception if the value is invalid).
Your code has multi threading issue, best create locally in your convert function to avoid it (otherwise you will have troubles with multiple thread as this class is not thread-safe)
Answer to your question is (using old Date api) - you can use Calendar to do it:
public static Date toCardDateFormat(String date){
Date result = null;
try {
result = new SimpleDateFormat("yyMMdd", Locale.getDefault()).parse(date);
} catch (ParseException e) {
return null; // or better throw exception or return Optional.empty()
}
Calendar cal = Calendar.getInstance();
cal.setTime(result);
cal.set(Calendar.DAY_OF_MONTH, 1);
return cal.getTime();
}
you could try something like this:
String[] arr = date.split("-");
String newDate = arr[0] + "-" + arr[1] + "-01";
private static final DateTimeFormatter CARD_DATE_FORMAT
= DateTimeFormatter.ofPattern("yyMMdd", Locale.getDefault());
public static Optional<YearMonth> toCardDateFormat(String date) {
try {
return Optional.of(YearMonth.parse(date, CARD_DATE_FORMAT));
} catch (DateTimeParseException e) {
return Optional.empty();
}
}
Don’t return null from a method. The risk of a NullPointerException on the caller’s side would be great. If you believe that not returning a value is the right thing in case of a string in the wrong format or containing an invalid date, use Optional to force the caller to take the possibility of no return value into account. Another obvious option is to leave any parsing exception to the caller:
public static YearMonth toCardDateFormat(String date) {
return YearMonth.parse(date, CARD_DATE_FORMAT);
}
DateTimeParseException is an unchecked exception, so needs not be declared in the method signature. Let’s try it:
System.out.println(toCardDateFormat("200908"));
This prints:
2020-09
Other messages:
I am using and warmly recommending java.time, the modern Java date and time API. The old date-time classes from Java 1.0 and 1.1 are now long outdated, and SimpleDateFormat in particular is notoriously troublesome. I think you should avoid them. The modern API is so much nicer to work with.
It seems you would really prefer to remove the day of month so you only have the month and year? The YearMonth class from java.time does exactly that for you. If instead you wanted a full date, use the LocalDate class as in xunts’ answer.
Link: Oracle tutorial: Date Time explaining how to use java.time.

How to check if a string is date?

I am having string like
"11-04-2015 22:01:13:053" or "32476347656435"
How can I check if string is Date?
Checking String if it is numeric using regex
String regex = "[0-9]+";
Other person are also correct
This is your answer
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class date {
public static boolean isValidDate(String inDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss:ms");
dateFormat.setLenient(false);
try {
dateFormat.parse(inDate.trim());
} catch (ParseException pe) {
return false;
}
return true;
}
public static void main(String[] args) {
System.out.println(isValidDate("20-01-2014"));
System.out.println(isValidDate("11-04-2015 22:01:33:023"));
System.out.println(isValidDate("32476347656435"));
}
}
java.time
It’s about time someone provides the modern answer. The SimpleDateFormat class mentioned in a couple of the other answers is notoriously troublesome and fortunately now long outdated. Instead the modern solution uses java.time, the modern Java date and time API.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-uuuu HH:mm:ss:SSS");
String stringToTest = "11-04-2015 22:01:13:053";
try {
LocalDateTime dateTime = LocalDateTime.parse(stringToTest, formatter);
System.out.println("The string is a date and time: " + dateTime);
} catch (DateTimeParseException dtpe) {
System.out.println("The string is not a date and time: " + dtpe.getMessage());
}
Output from this snippet is:
The string is a date and time: 2015-04-11T22:01:13.053
Suppose that instead the string was defined as:
String stringToTest = "32476347656435";
Now the output is:
The string is not a date and time: Text '32476347656435' could not be parsed at index 2
Link: Oracle tutorial: Date Time explaining how to use java.time.
There are two possible solutions:
Use a SimpleDateFormat and try to convert the String to Date. If no ParseException is thrown the format is correct.
Use a regular expression to parse the String
You can use Apache Commons Validator. It provides validation framework for validating date, time, numbers, currency, IP address, email, and URL.
Maven dependency:
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.6</version>
</dependency>
Example:
assertTrue(GenericValidator.isDate("2019-02-28", "yyyy-MM-dd", true))
The best solution is to actually try to parse it to a date with DateTime.TryParse().
String d = "11-04-2015 22:01:13:053";
DateTime dt = new DateTime();
if (DateTime.TryParse(d, out dt)) {
/// yes, it's a date, do something here...
} else {
// no, it's not a date, do something else here...
}

Adding specific characters in specific positions within a string in Java

I am storing date values within a SQLite database in the format 20121224 (so that I can easily sort the database by date) my question is how can I get the date from the format "20121224" to "2012/12/24" after being extracted from the database using java code.
You can do this.
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test003 {
public static void main(String[] args) throws Exception {
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd");
String s = "20121224";
Date dt = sdf1.parse(s);
System.out.println(sdf2.format(dt));
}
}
private static final String DATE_FORMAT = "yyyy/MM/dd";
private static final SimpleDateFormat dateFormat = new
SimpleDateFormat(DATE_FORMAT);
public static long dateAsLong(Calendar cal){
return Long.parseLong(dateFormat.format(cal.getTime()));
}
public static Calendar dateAsCalendar(long l){
try {
Calendar c = Calendar.getInstance();
c.setTime(dateFormat.parse(String.valueOf(l)));
return c;
} catch (ParseException e) {
return null;
}
}
Hope this helps.
In Java, Strings are immutable, so you can't modify the String you get back from the database; you have to make a new one. Easiest way, if your dates are guaranteed to be in yyyyMMdd format (ie, you don't store January as "01"), and you just want another String to come out the other end:
StringBuilder date = new StringBuilder();
date.append(dateStr.substring(0,4));
date.append("/");
date.append(dateStr.substring(4,6));
date.append("/");
date.append(dateStr.substring(6,8));
// use date.toString() wherever you need it
However, I'd recommend looking into how SQLite recommends you store dates. These are common formats and will allow you to use Java's built-in Date and DateFormat class in more conventional and convenient ways.
I see someone else has beaten me to submitting an answer while I was typing this...that suggestion will work, but it has you constructing 2 SimpleDateFormat objects, which isn't necessarily the most efficient way to go. Depends on how often you're doing this.
You can use the strftime function
Syntax:
strftime(timestring, modifiers...)
This returns the date formatted according to the format string specified
Example:
SELECT strftime('%d-%m-%Y') from TABLE_NAME;
Output:
24-11-2013
You can find all the formatters here

How to create a generic date formatter in java for Solr?

I've a requirement where date can be passed in the following formats before indexing them to Solr. Here are the examples of dates being passed
String dateStr = "2012-05-23T00:00:00-0400";
String dateStr1 = "May 24, 2012 04:57:40 GMT";
String dateStr2 = "2011-06-21";
The standard Solr format is "yyyy-MM-dd'T'HH:mm:ss'Z'".
I've tried SimpleDateFormat but is not able to write a generic program to support various formats. It ends up throwing parse exceptions.
I also tried joda time, but not been succeful so far in UTC conversion.
public static String toUtcDate(final String iso8601) {
DateTime dt = ISO_PARSE_FORMAT.parseDateTime(iso8601);
DateTime utcDt = dt.withZone(ZONE_UTC);
return utcDt.toString(ISO_PRINT_FORMAT);
}
Is there a standard library to achieve this ?
Any pointers will be appreciated.
Thanks
I just try the various formats until I get a hit:
public static String toUtcDate(String dateStr) {
SimpleDateFormat out = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
// Add other parsing formats to try as you like:
String[] dateFormats = {"yyyy-MM-dd", "MMM dd, yyyy hh:mm:ss Z"};
for (String dateFormat : dateFormats) {
try {
return out.format(new SimpleDateFormat(dateFormat).parse(dateStr));
} catch (ParseException ignore) { }
}
throw new IllegalArgumentException("Invalid date: " + dateStr);
}
I'm not aware of a library that does this.
Here is the answer:
Converting ISO 8601-compliant String to java.util.Date
Once you have your Date, you know how to get your UTC time.
Edit:
The accepted answer doesn't use joda time but jaxb.
By the way, where do these formats come from?
String dateStr = "2012-05-23T00:00:00-0400";
String dateStr1 = "May 24, 2012 04:57:40 GMT";
String dateStr2 = "2011-06-21";
If they are different from a locale to another, it may be possible they were generated by DateFormat.getDateTimeInstance(...,...) so perhaps try to figure out which has been used.

Categories

Resources