String Date Java - java

// Im new to java programming
I have a String object that represents a date/time in this format : "2013-06-09 14:20:00" (yyyy-MM-dd HH:mm:ss)
I want to convert it to a Date object so i can perform calculations on it but im confused on how to do this.
I tried :
String string = "2013-06-09 14:20:00";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(string);
System.out.println(date);
//Prints Mon Dec 31 00:00:00 GMT 2012
Any help appreciated
Ok so I have now updated my code to as follows i'm getting the correct date/time now when I print the date but is this the correct implementation :
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String string = "2013-06-09 14:20:00";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(string);
System.out.println(dateFormat.format(date));
//prints 2013-06-09 14:20:00
Thx to everyone that's answered/commented thus far

The format is wrong. Use this instead:
"yyyy-dd-MM HH:mm:ss"
Indeed your last program version is ok, except you don't need to declare the SimpleDateFormat twice. Simply:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String string = "2013-06-09 14:20:00";
Date date = dateFormat.parse(string);
System.out.println(dateFormat.format(date));

String string = "2013-06-09 14:20:00";
and the DATE object format is "yyyy-dd-MM HH:mm:ss"
You can get Date,Day,month and many more by using Date object which is present in
java.util.Date package , like as follows.
Date d = new Date(string);
This will call constructor of Date object for which you are passing 'string' variable which contains date.
d.getDay(); // retrieve day on that particular day
d.getDate(); // retrieve Date
and many more are avaiable like this.

Using java.util.Date
The answer by zzKozak is correct. Well, almost correct. The example code omits required exception handling. Like this…
java.text.DateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String string = "2013-06-09 14:20:00";
Date date = null;
try {
date = dateFormat.parse(string);
} catch ( ParseException e ) {
e.printStackTrace();
}
System.out.println("date: " + dateFormat.format(date));
Don't Use java.util.Date!
Avoid using java.util.Date & Calendar classes bundled with Java. They are notoriously bad in both design and implementation.
Instead use a competent date-time library. In Java that means either:
The third-party open-source Joda-Time
In the forthcoming Java 8, the new java.time.* classes defined by JSR 310 and inspired by Joda-Time.
Time Zone
Your question and code fail to address the issue of time zones. If you ignore time zones, you'll get defaults. That may cause unexpected behaviors when deployed in production. Better practice is to always specify a time zone.
Formatter
If you replace a space with a 'T' per the standard ISO 8601 format, then you can conveniently feed that string directly to a constructor of a Joda-Time DateTime instance.
If you must use that string as-is, then define a formatter to specify that format. You can find many examples of that here on StackOverflow.com.
Example Code
Here is some example code using Joda-Time 2.3, running in Java 7.
I arbitrarily chose a time zone of Montréal.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
// Specify a time zone rather than rely on default.
// Necessary to handle Daylight Saving Time (DST) and other anomalies.
DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" );
DateTime dateTime = new DateTime( "2013-06-09T14:20:00", timeZone ); // Or pass DateTimeZone.UTC as time zone for UTC/GMT.
System.out.println( "dateTime: " + dateTime );
When run…
dateTime: 2013-06-09T14:20:00.000-04:00

Related

Java, unparsable date error, converting from String to Date

I have this String "2019-10-17T16:00:00+02:00" and I want to convert this String to a Date object, because I want to change the format. I tried this:
SimpleDateFormat sd1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
Date dt = sd1.parse(mystring);
SimpleDateFormat sd2 = new SimpleDateFormat("yyyy-MM-dd");
String newDate = sd2.format(dt);
System.out.println(newDate);
But I have this message: Unparseable date: "2019-10-17T16:00:00+02:00"
What can I do?
Thank you all
For the sake of being up to date:
Please consider using the modern date and time API java.time.
You can easily parse and format dates, times and date times using it.
See this example:
public static void main(String[] args) {
String d = "2019-10-17T16:00:00+02:00";
OffsetDateTime odt = OffsetDateTime.parse(d, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
System.out.println(odt.format(DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss Z")));
}
The output is this:
2019/10/17 16:00:00 +0200
That formatter is used be default, so no need to specify. The standard ISO 8601 formats are used by default in java.time.
OffsetDateTime.parse( "2019-10-17T16:00:00+02:00" ) // ISO 8601 formats can be parsed directly, without specifying a `DateTimeFormatter` object.
If you just want to extract the date part of a date time, then you can do that, too by just applying two additional lines of code:
LocalDate date = odt.toLocalDate();
System.out.println(date.format(DateTimeFormatter.ISO_DATE));
The pattern letter for ISO 8601 time zones is X not Z as others have noted.
Use:
SimpleDateFormat sd1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
And parsing will succeed.

Format String yyyy-mm-dd hh:mm:ss +timezone into DateTime

I need to format a String that looks like this:
"2018-07-20 18:53:46.598000 +02:00:00"
into a DateTime object like this:
20/07/2018 (HH with Timezone applied):53:46
My approach has been:
String dateTimePattern = "dd/MM/yyyy HH:mm:ss";
SimpleDateFormat dateTimeFormat = new SimpleDateFormat(dateTimePattern);
Date feUltModDateTime = dateTimeFormat.parse(feUltMod);
feUltMod = feUltModDateTime.toString();
But I'm getting a parse error:
java.text.ParseException: Unparseable date: "2018-07-20 18:53:46.598000 +02:00:00"
java.time
DateTimeFormatter origFormatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSSSSS XXXXX");
DateTimeFormatter desiredFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu HH:mm:ss");
ZoneId desiredZone = ZoneId.of("America/Fort_Nelson");
String feUltMod = "2018-07-20 18:53:46.598000 +02:00:00";
OffsetDateTime dateTime = OffsetDateTime.parse(feUltMod, origFormatter);
ZonedDateTime dateTimeWithTimeZoneApplied = dateTime.atZoneSameInstant(desiredZone);
feUltMod = dateTimeWithTimeZoneApplied.format(desiredFormatter);
System.out.println(feUltMod);
Output from this snippet is:
20/07/2018 09:53:46
Generally you need two formatters for converting a date or date-time from one format to another: one that specifies the format to convert from and one that specifies the format to convert to.
into a DateTime object like this
A date-time object doesn’t have a format, so in that respect cannot be “like this”. dateTimeWithTimeZoneApplied in the above snippet is in the specified time zone, so has the hours adjusted. After converting to this time zone I have formatted into a string in the format you mentioned, in case you wanted this (I didn’t find it clear).
I am using and recommending java.time, the modern Java date and time API. The date and time classes you were using, Date and SimpleDateFormat, are long outdated and poorly designed, it’s not worth struggling with them. Also SimpleDateFormat supports only milliseconds so can only work correctly with exactly 3 decimals on the seconds, not with the 6 decimals you have got.
Link: Oracle tutorial: Date Time explaining how to use java.time.
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date df = new Date();
String yourString = sdf.format(df);
Date parsedDate = sdf.parse(yourString);
Timestamp sqlDate = new java.sql.Timestamp(parsedDate.getTime());
The above code will give you current Timestamp.Timestamp will provide better feasibilty

Timestamp string to timestamp in java

I have the following string "2015-04-02 11:52:00+02" and I need to parse it in Java to a Timestamp.
I tried all sorts of formats including
SimpleDateFormat mdyFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss+Z");
but nothing seems to work - I keep getting a ParseException
Can anyone help?
I need something like:
SimpleDateFormat mdyFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss+Z");
Timestamp t = new Timestamp(mdyFormat.parse("2015-04-02 11:52:00+02").getTime());
Try This
String str="2009-12-31 23:59:59 +0100";
/\
||
Provide Space while providing timeZone
SimpleDateFormat mdyFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
System.out.println(mdyFormat.parse(str));
Output
Fri Jan 01 04:29:59 IST 2010
java.sql.Timestamp objects don't have time zones - they are instants in time, like java.util.Date
So try this:
SimpleDateFormat mdyFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Timestamp t = new Timestamp(mdyFormat.parse("2015-04-02 11:52:00").getTime());
try "yyyy-MM-dd HH:mm:ssX"
Z stand for timezone in the following format: +0800
X stand for timezone in the following format: +08
Examples here
ISO 8601
Replace that SPACE in the middle with a T and you have a valid standard (ISO 8601) string format that can be parsed directly by either the Joda-Time library or the new java.time package built into Java 8 (inspired by Joda-Time). Search StackOverflow for hundreds of examples.
If using java.time, read my comment on Question about a bug when parsing hours-only offset value.
Example in Joda-Time 2.7.
String inputRaw = "2015-04-02 11:52:00+02";
String input = inputRaw.replace( " ", "T" );
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" ); // Specify desired time zone adjustment.
DateTime dateTime = new DateTime( input, zone );

Convert Java String with GMT date and -6 at end to CST [duplicate]

This question already has answers here:
Date and time conversion to some other Timezone in java
(11 answers)
Closed 8 years ago.
I have a string with gmt date value and -06:00 at end. What is best way to convert this to CST? I looked at other questions but none of them have -06:00 at end to answer my question.
This is what I tried and it errors out as java.text.ParseException: Unparseable date: "2015-02-19T11:50:09.5953377-06:00"
private DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss:SSSSSSS'Z'");
private DateFormat gmtFormat = new SimpleDateFormat();
private TimeZone cstTime = TimeZone.getTimeZone("CST");
gmtFormat.setTimeZone(cstTime);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
try {
System.out.println("cst start date is " + gmtFormat.format("2015-02-19T11:50:09.5953377-06:00"));
} catch (ParseException e) {
e.printStackTrace();
}
I've run into similar problems before, where I was actually getting dates in 3 different iso formats like that, and was pretty frustrated with it... This isn't pretty, but it may help point you in the right direction...
The 3 formats I was getting the info in:
private static final String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
private static final String ISO_FORMAT2 = "yyyy-MM-dd'T'HH:mm:ss'Z'";
private static final String ISO_FORMAT3 = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
Actually attempting to parse them (without having to figure out the correct type beforehand, returning a new Date Object in the event all 3 failed so shit doesn't crash because of a damn date formatting exception):
public static Date parseIso(String date){
SimpleDateFormat sdf = new SimpleDateFormat(ISO_FORMAT, Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
return sdf.parse(date);
}
catch (ParseException e) {
Log.g(TAG, "Failed 1st date parse with " + ISO_FORMAT + " for " + date);
sdf = new SimpleDateFormat(ISO_FORMAT2, Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
return sdf.parse(date);
}
catch (ParseException e2) {
Log.g(TAG, "Failed 2nd date parse with " + ISO_FORMAT2 + " for " + date);
sdf = new SimpleDateFormat(ISO_FORMAT3, Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
return sdf.parse(date);
}
catch (ParseException e3) {
Log.g(TAG, "Failed 3rd date parse with " + ISO_FORMAT3 + " for " + date);
}
}
}
return new Date();
}
And then for actually converting that date to a localized date:
public static String format(long mils, String format){
return format(getInstance(mils), format);
}
public static String format(Calendar calendar, String format){
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
return sdf.format(new Date(calendar.getTime().getTime() + TimeZone.getDefault().getOffset(new Date().getTime())));
}
public static Calendar getInstance(long timeInMils){
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
cal.setTimeInMillis(timeInMils);
return cal;
}
So now you can basically call
CalendarHelper.format(myDateObject.getTime(), "MMM dd, yyyy");
and it will return the localized, formatted date from the original UTC date you received.
Again, not pretty, but I hope this can point you in the right direction for converting between the UTC and client's time zone. Best of luck~
PS. I think ISO_FORMAT_3 is the one that will actually help you. I guess I probably could have started with that information, but I'm not a bright man.
ISO 8601
You seem to misunderstand the meaning of the input string, 2015-02-19T11:50:09.5953377-06:00. You do not have a "gmt date value".
That format appears to be the standard ISO 8601 format.
The T in the middle separates the date portion from the time-of-day portion.
The -06:00 at the end is an offset from UTC. It means "the date-time value shown here is six hours behind UTC".
CST
So, if by CST you mean Central Time Zone (some of the middle parts of the Americas continents), then you need have no conversion to perform. That string with the time 11:50 means "almost noon in Illinois, Arkansas, and Louisiana". If you add 6 hours to 11:50, you would learn the UTC (GMT) date-time at that same moment: 17:50 on same date.
Avoid 3-4 Letter Codes
By the way, avoid using three or four letter time zone codes such as "CST". Those codes are not standardized nor unique. Many duplicates exist. For example, take CST:
Central Standard Time (Americas)
China Standard Time
Central Standard Time (Australia)
Central Summer Time (Australia)
Cuba Standard Time
Instead use proper time zones. Most of these are continent plus a slash plus a city/region. Examples: America/Regina, America/Monterrey, and America/Indiana/Knox.
Joda-Time | java.time
The java.util.Date/.Calendar classes are notoriously troublesome. Avoid them.
Use either the Joda-Time library or the new java.time package built into Java 8. The java.time package is inspired by Joda-Time but is re-architected. Each has its own strengths and weaknesses.
Both Joda-Time and java.time use ISO 8601 formats as their defaults for both parsing and generating string representations of date-time values.
As this Question is really a duplicate with hundreds of such Questions and Answers already posted, I'll give just one quick example.
String input = "2015-02-19T11:50:09.5953377-06:00";
DateTimeZone zoneAmerica_Regina = DateTimeZone.forID( "America/Regina" );
DateTime dateTimeAmericaRegina = new DateTime( input, zoneAmerica_Regina );
DateTime dateTimeLosAngeles = dateTimeAmericaRegina.withZone( DateTimeZone.forID( "America/Los_Angeles" ) );
DateTime dateTimeUtc = dateTimeAmericaRegina.withZone( DateTimeZone.UTC );
Fractional Seconds
Your input string has a very small fraction of a second. Joda-Time (like java.util.Date) handles only millisecond resolution — three digits after the decimal point. The java.item package handles nanosecond resolution. Some systems use microsecond resolution, such as database like Postgres. And some systems follow the old Unix convention of whole seconds.

How to parse time from date string retrieved from Facebook

I'm getting these times from Facebook events. E.g: start_time and it's a string like this:
2013-12-21T18:30:00+0100
Now I just want the time, like:
18.30
I tried to do it with this:
SimpleDateFormat formatter = new SimpleDateFormat(" EEEE, dd MMMM yyyy", java.util.Locale.getDefault());
Date formatted = null;
try {
formatted = formatter.parse(p.getStart_time());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String formattedString = formatted.toString();
txtStart_time.setText(""+formattedString);
p.getStart_time() is a String that gives me the date like I said before.
If I do this method, I get an error:
Unparseable date.
Does anybody know a work around?
You need two formats: one to parse the date and one to format it
String startTime = "2013-12-21T18:30:00+0100";
SimpleDateFormat incomingFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
Date date = incomingFormat.parse(startTime);
SimpleDateFormat outgoingFormat = new SimpleDateFormat(" EEEE, dd MMMM yyyy", java.util.Locale.getDefault());
System.out.println(outgoingFormat.format(date));
prints
Saturday, 21 December 2013
I'm getting these times from Facebook events. E.g: start_time and it's
a string like this:
2013-12-21T18:30:00+0100
Now I just want the time, like:
18.30
Solution using java.time, the modern date-time API:
OffsetDateTime.parse(
"2013-12-21T18:30:00+0100",
DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssZ")
).toLocalTime()
Description: Your date-time string has a timezone offset of +01:00 hours. java.time API provides you with OffsetDateTime to contain the information of date-time units along with the timezone offset. Using the applicable DateTimeFormatter, parse the string into an OffsetDateTime and then get the LocalTime part of this date-time using OffsetDateTime#toLocalTime.
Demo using java.time API:
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
class Main {
public static void main(String[] args) {
System.out.println(OffsetDateTime.parse(
"2013-12-21T18:30:00+0100",
DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssZ")
).toLocalTime());
}
}
Output:
18:30
ONLINE DEMO
Note: You can use y instead of u here but I prefer u to y.
Learn more about the modern Date-Time API from Trail: Date Time.
A note about the legacy API:
The question and the accepted answer use java.util.Date and SimpleDateFormat which was the correct thing to do in 2013. In Mar 2014, the java.util date-time API and their formatting API, SimpleDateFormat were supplanted by the modern date-time API. Since then, it is highly recommended to stop using the legacy date-time API.
Use something like yyyy-MM-dd'T'HH:mm:ssZ as parsing format instead of EEEE, dd MMMM yyyy.
Substring
If all you want is literally the time component lifted from that string, call the substring method on the String class…
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
String dateTimeStringFromFacebook = "2013-12-21T18:30:00+0100";
// Extract a substring.
String timeSubstring = dateTimeStringFromFacebook.substring( 11, 19 );
DateTime Object
If you want the time converted to a particular time zone, convert the string to a date-time object. Use a formatter to express just the time component.
Here is some example code using the Joda-Time 2.3 library. Avoid the notoriously bad java.util.Date/Calendar classes. Use either Joda-Time or the new java.time.* JSR 310 classes bundled with Java 8.
// From String to DateTime object.
DateTime dateTime = new DateTime( dateTimeStringFromFacebook, DateTimeZone.UTC );
// From DateTime object to String
// Extract just the hours, minutes, seconds.
DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm:ss");
String timeFragment_Paris = formatter.withZone( DateTimeZone.forID( "Europe/Paris" ) ).print( dateTime );
String timeFragment_Kolkata = formatter.withZone( DateTimeZone.forID( "Asia/Kolkata" ) ).print( dateTime ); // Formerly known as Calcutta, India.
Dump to console…
System.out.println( "dateTimeStringFromFacebook: " + dateTimeStringFromFacebook );
System.out.println( "timeSubstring: " + timeSubstring );
System.out.println( "dateTime: " + dateTime );
System.out.println( "timeFragment_Paris: " + timeFragment_Paris );
System.out.println( "timeFragment_Kolkata: " + timeFragment_Kolkata + " (Note the 00:30 difference due to +05:30 offset)");
When run…
dateTimeStringFromFacebook: 2013-12-21T18:30:00+0100
timeSubstring: 18:30:00
dateTime: 2013-12-21T17:30:00.000Z
timeFragment_Paris: 18:30:00
timeFragment_Kolkata: 23:00:00 (Note the 00:30 difference due to +05:30 offset)
Think Time Zone
Your question fails to address the question of time zone. Make a habit of always thinking about time zone whenever working with date-time values. If you mean the same time zone, say so explicitly. If you mean the default time zone of the Java environment, say so. If you mean UTC… well, you get the idea.

Categories