Java Reflection - calling a a date function - java

I am getting a string "Date.UTC(2013,10,9,0,0,0)" from a function return. I want to construct a date out of it. something like "2013-10-09 00:00:00"
Can I use reflection to give me a timestamp from the string?
Or do I have to use a substring and split based on "," and construct the date string?

Use a SimpleDateFormat with a pattern appropriate for your input format:
Date date = new SimpleDateFormat("'Date.UTC('yyyy,MM,dd,HH,mm,ss)").parse(str);
Here's some test code:
String str = "Date.UTC(2013,10,9,0,0,0)";
Date date = new SimpleDateFormat("'Date.UTC('yyyy,MM,dd,HH,mm,ss)").parse(str);
System.out.println(date);
Output:
Wed Oct 09 00:00:00 EST 2013
Note that Date objects carry no formatting information. If you want to print a Date in a particular format, create a DateFormat for that purpose.

To parse a DateTime in any Format, you should have a look at http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html, especially at the method parse()
The API will serve any further information you need to accomplish your goal.

Nope, no need for reflection nor string-splitting. Let a date-time formatter do the parsing work for you.
The answer by Bohemian is correct technically. But not advisable. The bundled java.util.Date and Calendar are notoriously troublesome and should be avoided. Use either Joda-Time or the new java.time.* package found in Java 8.
Example Code
String input = "Date.UTC(2013,10,9,0,0,0)";
DateTimeFormatter formatter = DateTimeFormat.forPattern( "'Date.UTC('yyyy,MM,dd,HH,mm,ss)" ).withZone( DateTimeZone.UTC );
DateTime dateTime = formatter.parseDateTime( input );
System.out.println( "dateTime: " + dateTime );
System.out.println( "dateTime in India: " + dateTime.withZone( DateTimeZone.forID( "Asia/Kolkata" ) ) );
When run…
dateTime: 2013-10-09T00:00:00.000Z
dateTime in India: 2013-10-09T05:30:00.000+05:30

Related

Get only TimeZone field from new Date() in java

Requirement : I want to get only TimeZone field from new Date(), As of now from new Date() ,I am getting result as
Wed Jul 23 19:37:20 GMT+05:30 2014,But I want only GMT+05:30,Is there any way to get only this?
PS:I dont want to use split for getting timezone field.because this is my final option for achieving above requirement.
You should use the Calendar class and likely, the implementation GregorianCalendar. A lot of the Date functions have been deprecated in favor of using Calendar. Java 8 has the Clock API, but I'll assume Java 7 here.
That way you can do this:
Calendar calendar = new GregorianCalendar();
TimeZone tz = calendar.getTimeZone();
And work from there.
Assuming you have to work with a String input you can do something like this:
// format : dow mon dd hh:mm:ss zzz yyyy
String date = "Wed Jul 23 19:37:20 GMT+05:30 2014";
Pattern pattern = Pattern
.compile("^\\w{3}\\s\\w{3}\\s\\d{2}\\s\\d{2}:\\d{2}:\\d{2}\\s?(.*)\\s\\d{4}$");
Matcher matcher = pattern.matcher(date);
if (matcher.matches()) {
String timezone = matcher.group(1);
// beware : according to the Date.toString() documentation the timezone
// value can be empty
System.out.println(timezone);
} else {
System.out.println("doesn't match!");
}
import java.util package and use GregorianCalendar method.
int second, minute, hour;
GregorianCalendar date = new GregorianCalendar();
second = date.get(Calendar.SECOND);
minute = date.get(Calendar.MINUTE);
hour = date.get(Calendar.HOUR);
System.out.println("Current time is "+hour+" : "+minute+" : "+second);
Don't use Date and Time class of java.util package as their methods are deprecated means they may not be supported in future versions of JDK.
Generate String With Offset But No Date and No Time
Your question is inaccurate. A java.util.Date has no time zone (assumes to always be in UTC). The JVM's time zone is applied in the object' toString method and in other formatting code that generates a String representation. Therein lies your solution: use a date-time formatter that generates a String containing only the offset from UTC without the date or the time-of-day portions.
Avoid java.util.Date & .Calendar
Avoid using the bundled java.util.Date and .Calendar classes as they are notoriously troublesome. Instead use either Joda-Time or the new java.time package. Both support time zones as part of a date-time object.
Joda-Time
Here is how to generate a String representation of a DateTime in Joda-Time 2.3.
DateTime dateTime = new DateTime( DateTimeZone.forID( "Asia/Kolkata" ) );
DateTimeFormatter formatter = DateTimeFormat.forPattern( "ZZ" );
String offset = formatter.print( dateTime ); // generates: +05:30
In Joda-Time 2.3 you can ask a DateTime object for its assigned time zone as an object. You may then interrogate the DateTimeZone object.
DateTime dateTime = new DateTime( DateTimeZone.forID( "Asia/Kolkata" ) );
DateTimeZone timeZone = dateTime.getZone();
String id = timeZone.getID();

Converting calendar to date in dd-MMM-yyyy format

I am trying to add 17 days to 10-APR-2014 and convert the date to dd-MMM-yyyy format, but I am getting Sun Apr 27 00:00:00 GMT+05:30 2014.
Here is my code:
import java.util.*;
import java.text.*;
public class HelloWorld{
public static void main(String []args){
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.DATE, 17);
String output = sdf.format(c.getTime());
System.out.println(output);
System.out.print(new SimpleDateFormat("dd-MMM-yyyy").parse(output));
}
}
How can I make the output be 27-Apr-2014?
You are printing a Date parsed from a String formatted from the calendar date.
Instead, print the formatted calendar date:
System.out.print(new SimpleDateFormat("dd-MMM-yyyy").format(c.getTime()));
If displaying and using the dates is disjunct, do this:
Date date; // from Calendar or wherever
String str = new SimpleDateFormat("dd-MMM-yyyy").format(date));
// display str
Then when you want to do something with a selected date:
String selection;
Date date = new SimpleDateFormat("dd-MMM-yyyy").parse(selection));
// do something with date
The answer by Bohemian is correct. Here I present an alternative solution.
Avoid j.u.Date
The java.util.Date and .Calendar classes bundled with Java are notoriously troublesome. Avoid them. Use either Joda-Time or the new java.time package in Java 8.
Date-Only
If you need only a date, without any time component, both Joda-Time and java.time offer a LocalDate class.
Time Zone
Even for a date-only, you still need a time zone to get "today". At any moment the date may vary ±1 depending on your location on the globe. If you do not specify a time zone, the JVM's default time zone will be applied.
Example Code
Here is some example code in Joda-Time 2.3.
Determine "today" based on some time zone. Add seventeen days.
DateTimeZone timeZone = DateTimeZone.forID( "Asia/Kolkata" );
LocalDate today = new LocalDate( timeZone );
LocalDate seventeenDaysLater = today.plusDays( 17 );
Generate a String representation of the date-time value…
DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd-MMM-yyyy" );
String output = formatter.print( seventeenDaysLater );
Dump to console…
System.out.println( "today: " + today );
System.out.println( "seventeenDaysLater: " + seventeenDaysLater );
System.out.println( "output: " + output );
When run…
today: 2014-04-21
seventeenDaysLater: 2014-05-08
output: 08-May-2014

Handling timezone when parsing date in Java 6

I am trying to parse/validate the date 2013-06-19T12:00-05:00 using Java 6
I have tried several patterns, including following:
yyyy-MM-dd'T'HH:mmz
yyyy-MM-dd'T'HH:mmZ
yyyy-MM-dd'T'HH:mm'Z'
yyyy-MM-dd'T'HH:mm Z
yyyy-MM-dd'T'HH:mm z
yyyy-MM-dd'T'HH:mm'z'
yyyy-MM-dd'T'HH:mm-Z
yyyy-MM-dd'T'HH:mm-z
yyyy-MM-dd'T'hh:mm:ssZ
yyyy-mm-DD'T'hh:mm:ssZ
yyyy-MM-DD'T'hh:mm:ssZ
yyyy-MM-dd'T'HH:mm:ssZ
yyyy-MM-dd'T'HH:mm:ssz
but keep getting ParseException.
What would be the appropriate format/pattern for parsing 2013-06-19T12:00-05:00?
Thanks.
I would suggest that you use the excellent Joda-Time library to do this, specifically the parse(String str) method of the DateTime class, which will parse your example date using the default ISODateTimeFormat.dateTimeParser()
The JavaDoc for DateTime.parse(String str) is at http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html#parse%28java.lang.String%29 and you can read more about Joda-Time at http://www.joda.org/joda-time/
String dateString = "2013-06-19T12:00-05:00";
String pattern = "yyyy-MM-dd'T'HH:mmZ";
DateTimeFormatter dtf = DateTimeFormat.forPattern(pattern);
DateTime dateTime = dtf.parseDateTime(dateString);
Date ans=dateTime.toDate();
System.out.println(ans);
Use simpledateformat with pattern like "yyyy-MM-dd'T'HH-mm:ss:SS"
The Joda-Time 2.3 library is already built to handle that variation of ISO 8601 format. No need to create a formatter.
I arbitrarily chose Montréal Québec as a time zone because of your -05:00 time zone offset. You may rather work with UTC/GMT date-times in which case you can pass a pre-defined instance: DateTimeZone.UTC.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
String dateTimeString = "2013-06-19T12:00-05:00";
DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" ); // Or for UTC/GMT, use: DateTimeZone.UTC
DateTime dateTime = new DateTime( dateTimeString, timeZone );
Dump to console…
System.out.println( "dateTimeString: " + dateTimeString );
System.out.println( "dateTime: " + dateTime );
System.out.println( "dateTime in UTC/GMT: " + dateTime.toDateTime( DateTimeZone.UTC ) );
When run…
dateTimeString: 2013-06-19T12:00-05:00
dateTime: 2013-06-19T13:00:00.000-04:00
dateTime in UTC/GMT: 2013-06-19T17:00:00.000Z
Note the one hour difference because Montréal Québec was in Daylight Saving Time (DST) on that date.
The date 2013-06-19T12:00-05:00 can't be parsed under Java 6 in current form. On other hand using Joda-Time seems to be an overkill.
To solve problem I added timezone to the date:
public Date extractDate(String dateStr) {
Pattern aPattern = Pattern.compile("\\d+([+-]\\d+:\\d+)$", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
Matcher matcher = aPattern.matcher(dateStr);
if(matcher.find()){
String timezone = matcher.group(1);
System.out.println("timezone:" + timezone);
dateStr = StringUtils.replace(dateStr, timezone, "GMT" + timezone);
}
Date date = null;
String [] datePatterns = {"yyyy-MM-dd'T'HH:mmZ"};
try {
date = DateUtils.parseDateStrictly(dateStr, datePatterns);
}
catch (Exception except) {
except.printStackTrace();
}
return date;
}

DateFomat give unparsable date error?

if I have a string date:
2013-11-14T00:00:00.000
What date format can I use to create a date with the offset?
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
dateFormat.setTimeZone(TimeZone.getDefault());
Date date = dateFormat.parse(myDate);
The above gives an unparsable date error.
"yyyy-MM-dd'T'HH:mm:ss.SSS"
Use SSS for milliseconds and remove Z as the date string does not have a time zone.
If you intend to print/log the date in another format (with a custom time zone, for example), you will have to use another instance of DateFormat:
"yyyy-MM-dd'T'HH:mm:ss.SSS" // to parse the date string
"yyyy-MM-dd'T'HH:mm:ss.SSSZ" // to format the date object
The .000 on the end is not a time zone designation; it looks like milliseconds. Try replacing the Z time zone designation with SSS for milliseconds.
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
your supplied 2013-11-14T00:00:00.000 is not specified with the above pattern: "yyyy-MM-dd'T'HH:mm:ss.SSS Z" as sample valid input for this pattern would be:
2013-11-14T00:00:00.000 -0700
Either drop the Z or pass a string as the mentioned sample.
FYI, here is that same kind of code using Joda-Time 2.3.
Joda-Time uses that kind of ISO 8601 format as its default. No need for a formatter to parse that string. Merely pass the string to a DateTime constructor. The constructor automatically invokes a built-in ISO formatter.
String input = "2013-11-14T00:00:00.000";
// Specify a time zone rather than rely on default.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime dateTime = new DateTime( input, timeZone );
System.out.println( "dateTime: " + dateTime );
When run…
dateTime: 2013-11-14T00:00:00.000+01:00
If you need a java.util.Date for use with other classes, convert from Joda-Time.
java.util.Date date = dateTime.toDate();

Formatting the DATE in JSON response

I am getting date as below in json response .
{"dateTime":"2012-03-03T10:00:00.890+05:30"}
I wated to display it like 3 march 2012 10Am in java . How to format this date
If you want to do it in Java, Use SimpleDateFormat like this:
EDIT:
To match with your scenario I have edited it as follows:
String input = "2012-03-03T10:00:00.890+05:30";
In the above input string you will have to remove the : colon from the time zone part i.e. +05:30. You could use regex to do this as shown in this post. And then use following code to convert it in your format:
DateFormat oldFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
DateFormat newFormat = new SimpleDateFormat("dd MMMMM yyyy hha");
String dateStr = newFormat.format(oldFormat.parse(input));
In JS,this date is in standart format so new date(object.dateTime) will parse your date. Then by using toGMTString or toLocalString you will have the right format.
You just have to strip the 4 first and 4 last characters of the string returned.
what language are you using to display the date?
You would have to parse the value as a date, then you can change the format of the display of that date.
The answer by Kuldeep Jain is correct. But using the java.util.Date/Calendar classes should be avoided as they are badly designed and implemented.
Instead use Joda-Time, or in Java 8, the new java.time.* classes (inspired by Joda-Time).
While Joda-Time allows you to define your own specific formats for parsing, in your case you needn't. The constructors on Joda-Time's DateTime class are already built to parse the ISO 8601 format you are using.
Example code…
// © 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.*;
DateTimeZone timeZone_Kolkata = DateTimeZone.forID( "Asia/Kolkata" );
String input = "2012-03-03T10:00:00.890+05:30";
DateTime dateTime = new DateTime( input );
DateTime dateTimeInUtc = dateTime.toDateTime( DateTimeZone.UTC );
DateTime dateTimeInKolkata = dateTime.toDateTime( timeZone_Kolkata );
DateTimeFormatter formatter = DateTimeFormat.forStyle("LS").withLocale( new Locale( "en", "IN" ) ); // English, India.
String output = formatter.print( dateTime );
Dump to console…
System.out.println( "dateTime: " + dateTime );
System.out.println( "dateTimeInUtc: " + dateTimeInUtc );
System.out.println( "dateTimeInKolkata: " + dateTimeInKolkata );
System.out.println( "output: " + output );
When run…
dateTime: 2012-03-02T20:30:00.890-08:00
dateTimeInUtc: 2012-03-03T04:30:00.890Z
dateTimeInKolkata: 2012-03-03T10:00:00.890+05:30
output: 2 March, 2012 8:30 PM

Categories

Resources