Parse specific date string format - java

I have read a lot of questions and searched for a lot of libs all over the internet but I can't find one that can do this quickly.
I want to parse a specific date in a specific date format like this:
String date = "20130516T090000";
SimpleDateFormat x = new SimpleDateFormat("yyyyMMddTHHmmss");
String theMonth = x.parse(date, "M"); // 05
String theMonth = x.parse(date, "MMM"); // MAY
String theMinute = x.parse(date, "mm"); // 00
String theYear = x.parse(date, "yyyy"); // 2013
Just simple as that. A way to set a Parse Rule, a Specific Date Format and a way to retrieve each data i want (Month, Minute, Year....)
Is there a good library to do EXACTLY this? If yes could you put an example together? If no, is there a good way to do this without much code?
Thanks in advance!

Use the SimpleDateFormat class to parse a date from a String to a Date instance.
String date = "20130516T090000";
SimpleDateFormat x = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
Date d = x.parse(date);
There was a problem in your SimpleDateFormat format String, text in the format has to be quoted using single quoted (') to avoid interpretation.
Use the Calendar class to get the part of the date you want.
Calendar cal = Calendar.getInstance();
cal.setTime(d);
String theYear = String.valueOf(cal.get(Calendar.YEAR));
String theMonth = String.valueOf(cal.get(Calendar.MONTH));
String theMinute = String.valueOf(cal.get(Calendar.MINUTE));

Related

java.text.ParseException: Unparseable date when trying to convert "2013-07-01T04:37:14.771468Z" into Local time

I need to convert UTC time string I get into local time using following method,
String dateCreate = "2013-07-01T04:37:14.771468Z"
DateFormat dfParse = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss'Z'");
dfParse.setTimeZone(TimeZone.getTimeZone("UTC"));
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("Asia/Colombo"));
java.util.Date dateTime;
dateTime = dfParse.parse(dateCreate);
String dteCreate = df.format(dateTime);
Can someone plese give me a solution for this.? :)
EDIT: Now that I've checked it supports this easily, I'd strongly recommend that you use Joda Time. Its ISO-8601 parser works fine:
String dateCreate = "2013-07-01T04:37:14.771468Z";
DateTimeFormatter formatter = ISODateTimeFormat.dateTime();
DateTime parsed = formatter.parseDateTime(dateCreate);
By default that will convert to the system default time zone, but you can change that behaviour with calls on DateTimeFormatter.
Joda Time is also a much cleaner API than the built-in one - you'll find any date/time code is easier to write and easier to read.
Look at your input data and your pattern:
String dateCreate = "2013-07-01T04:37:14.771468Z";
DateFormat dfParse = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss'Z'");
They don't match at all. You need something like:
// Don't use this directly!
DateFormat dfParse = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'");
dfParse.setTimeZone(TimeZone.getTimeZone("UTC"));
Or:
// Don't use this directly!
DateFormat dfParse = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSX");
The latter will cope with any ISO-8601 time zone; the former restricts to UTC.
Unfortunately, the above will end up with the wrong number of milliseconds as it will take all the microseconds to be milliseconds. I don't know of a way of avoiding this in Java... you may need to trim the string first. For example:
// Remove the sub-millisecond part, assuming it's three digits:
int firstPartLength = "yyyy-MM-ddTHH:mm:ss.SSS".length();
String noMicros = dateCreate.substring(0, firstPartLength) +
dateCreate.substring(firstPartLength + 3);
// Now we've got text without micros, so create an appropriate pattern
DateFormat dfParse = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
Date date = dfParse.parse(noMicros);
Alternatively, if you know it's always going to end with "Z":
int firstPartLength = "yyyy-MM-ddTHH:mm:ss.SSS".length();
String noMicros = dateCreate.substring(0, firstPartLength);
DateFormat dfParse = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
dfParse.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = dfParse.parse(noMicros);
This is irritating, and it would be nice to be able to tell Java to treat any digits after the dot as "fractions of a second" but I don't know of any way of doing that using SimpleDateFormat. Note that you wouldn't be able to represent the sub-millisecond value using just Date anyway.
This is xsd dateTime format. You should use javax.xml.bind.DatatypeConverter for that
Calendar c = DatatypeConverter.parseDateTime(lexicalXSDDateTime);
Note that for SmipleDateFormat S means number of milliseconds so it will parse 771468 as 771468 ms not 0.771468 sec which adds extra 771 secs to the result date
Formatting part is OK

How to display the date format in android?

String date="21-04-2013";
In my android application
Here i want to display the date in the following format like "21" is a separate string and month is like "Apr" as a separate string and year is like "13"as a separate string without using String functions.Can anybody plz give some suggestions to convert in this format?any date function is available?
You'll want to take a look at the SimpleDateFormat class for parsing the date string. In order to end up separate strings without using string functions, you'll probably need multiple formatters for the output too. It would look somewhat like this:
String date = "21-04-2013";
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM-yyyy"); // input date
Date outDate = dateFormatter.parse(date);
SimpleDateFormat dayFormatter = new SimpleDateFormat("dd"); // output day
SimpleDateFormat monthFormatter = new SimpleDateFormat("MMM"); // output month
SimpleDateFormat yearFormatter = new SimpleDateFormat("yy"); // output year
String day = dayFormatter.format(outDate);
String monthy = monthFormatter.format(outDate);
String year = yearFormatter.format(outDate);
If you were to use String.split(), you could get rid of at least two of the formatters in above snippet.
This is the class you'll need: DateFormat
Examples are provided in the link, but in short, you'll first need to parse the date, and then format the date again.

SimpleDateFormat String

I have this code block where argument to dateFormat.format will always be a string thats why I did .toString() here. I am getting error "Cannot format given Object as a Date".
Is there any way to do this ? Note that string is coming from database I used new Date() as a sample here.
SimpleDateFormat dateFormat = new SimpleDateFormat("MMMMM dd, yyyy");
String sCertDate = dateFormat.format(new Date().toString());
DateFormat#format accepts a Date, not a string.
Use
String sCertDate = dateFormat.format(new Date());
If you have a string coming from the database that is a specific format and you want to convert into a date, you should use the parse method.
#Sonesh - Let us assume you have a string in the database that happens to represent a Date ( might be better to store the object in the database as dates? ) , then you would first parse it to the format you wanted and then format it to the string format you wanted.
// Assumes your date is stored in db with format 08/01/2011
SimpleDateFormat dateFormatOfStringInDB = new SimpleDateFormat("MM/dd/yyyy");
Date d1 = dateFormatOfStringInDB.parse(yourDBString);
SimpleDateFormat dateFormatYouWant = new SimpleDateFormat("MMMMM dd, yyyy");
String sCertDate = dateFormatYouWant.format(d1);
There are two applications of SimpleDateFormat:
parse a string - when you have a date represented as string, and you want to get the corresponding Date object. Then use dateFormat.parse(string)
format a date - when you have a Date object and you want to format it in a specific way (usually in order to show it to a user). In that case use dateFormat.format(date)
The two methods are reciprocal - one takes a date and returns a string, and the other takes a string and returns a date.
For your particular case, perhaps you need .parse(..). But note that every 'self-respecting' database driver should have an option to return a Date rather than some string representation. If you happen to be storing dates as string in the DB - don't do that. Use the native date type.
If you need to read a Date with one String format and output it to another String format, you need 2 formatters, for example:
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat outputFormat = new SimpleDateFormat("MMMMM dd, yyyy");
String output = outputFormat.format(inputFormat.parse(input));

Extract time from date String

How can I format the "2010-07-14 09:00:02" date string to depict just "9:00"?
Use DateTimeFormatter to convert between a date string and a real LocalDateTime object. with a LocalDateTime as starting point, you can easily apply formatting based on various patterns as definied in the javadoc of the DateTimeFormatter.
String originalString = "2010-07-14 09:00:02";
LocalDateTime dateTime = LocalDateTime.parse(originalString, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
String newString = DateTimeFormatter.ofPattern("H:mm").format(dateTime); // 9:00
In case you're not on Java 8 or newer yet, use SimpleDateFormat to convert between a date string and a real Date object. with a Date as starting point, you can easily apply formatting based on various patterns as definied in the javadoc of the SimpleDateFormat.
String originalString = "2010-07-14 09:00:02";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(originalString);
String newString = new SimpleDateFormat("H:mm").format(date); // 9:00
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2010-07-14 09:00:02");
String time = new SimpleDateFormat("H:mm").format(date);
http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html
A very simple way is to use Formatter (see date time conversions) or more directly String.format as in
String.format("%tR", new Date())
The other answers were good answers when the question was asked. Time moves on, Date and SimpleDateFormat get replaced by newer and better classes and go out of use. In 2017, use the classes in the java.time package:
String timeString = LocalDateTime.parse(dateString, DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss"))
.format(DateTimeFormatter.ofPattern("H:mm"));
The result is the desired, 9:00.
I'm assuming your first string is an actual Date object, please correct me if I'm wrong. If so, use the SimpleDateFormat object: http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html. The format string "h:mm" should take care of it.
If you have date in integers, you could use like here:
Date date = new Date();
date.setYear(2010);
date.setMonth(07);
date.setDate(14)
date.setHours(9);
date.setMinutes(0);
date.setSeconds(0);
String time = new SimpleDateFormat("HH:mm:ss").format(date);
let datestring = "2017-02-14 02:16:28"
let formatter = DateFormatter()
formatter.dateStyle = DateFormatter.Style.full
formatter.timeStyle = DateFormatter.Style.full
formatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
let date = formatter.date(from: datestring)
let date2 = formatter.String(from: date)

Java date format real simple

how would you write te date if i have a date and all i want is the month and the day like this (mm/dd) and then turn the month like this July, 08
Let me see if I understood well.
You have a date like "07/08" and you want "July, 08"?
You could try SimpleDateFormat
import java.text.SimpleDateFormat;
import java.text.ParseException;
class Test {
public static void main( String [] args ) throws ParseException {
SimpleDateFormat in = new SimpleDateFormat("MM/dd");
SimpleDateFormat out = new SimpleDateFormat("MMMM, dd");
System.out.println( out.format( in.parse("07/08") ) );
// Verbose
//String input = "07/09";
//Date date = in.parse( input );
//String output = out.format( date );
//System.out.println( output );
}
}
Use:
Format formatter = new SimpleDateFormat("MMMM, dd");
String s = formatter.format(date);
Formatting a Date Using a Custom Format
The SimpleDateFormat is your friend here. If you already have a java.util.Date object, just format it using the desired pattern (refer to the javadoc for details on date and time patterns):
SimpleDateFormat out = new SimpleDateFormat("MMMM, dd");
String s = out.format(date); // date is your existing Date object here
(EDIT: I'm adding some details as the original question is unclear and I may have missed the real goal.
If you have a String representation of a date in a given format (e.g. MM/dd) and want to transform the representation, you'll need 2 SimpleDateFormat as pointed out by others: one to parse the String into a Date and another one to format the Date.
SimpleDateFormat in = new SimpleDateFormat("MM/dd");
Date date = in.parse(dateAsString); // dateAsString is your String representation here
Then use the code snippet seen above to format it.)
the month and the day like this (mm/dd) and then turn the month like this July, 08
So you want to convert MM/dd to MMMM, dd? So you start with a String and you end up with a String? Then you need another SimpleDateFormat instance with the first pattern.
String dateString1 = "07/08";
Date date = new SimpleDateFormat("MM/dd").parse(dateString1);
String dateString2 = new SimpleDateFormat("MMMM, dd").format(date);
System.out.println(dateString2); // July, 08 (monthname depends on locale!).

Categories

Resources