After DateTimeZone.convertLocalToUTC timezone still shows local - java

I use DateTimeZone.convertLocalToUTC to convert local time to UTC. The time is changed correctly, but after conversion, the timezone info still says the Original local timezone. Please refer below sample code
Date gmttime = new Date(tz.convertLocalToUTC(System.currentTimeMillis(),false));
System.out.println(gmttime.toString());
Output :
Wed Oct 16 12:58:19 IST 2013
Please note the bold value, I expected it to be UTC . Please let me know if I am missing something.

#Date.toString() will print the date in the local timezone.
Use SimpleDateFormat to print the Date formatted for a specific TimeZone:
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat("E MMM dd HH:mm:ss:SS z");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(format.format(date));
}

Try:
final Date date = new Date();
final String ISO_FORMAT = "E MMM dd HH:mm:ss zzz yyyy";
final SimpleDateFormat sdf = new SimpleDateFormat(ISO_FORMAT);
final TimeZone utc = TimeZone.getTimeZone("UTC");
sdf.setTimeZone(utc);
System.out.println(sdf.format(date));
Output:
Wed Oct 16 08:53:50 UTC 2013

convertLocalToUTC Converts a local instant to a standard UTC instant with the same local time. http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTimeZone.html

Related

Parse a Date of MMMM YYYY format

I have to parse a date string (e.g. "October 2015") to a Date.
So the question is: how can I parse a date of MMMM yyyy format? Its ok if the new Date object is the first month of the given month.
I tried:
DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendPattern("MMMM yyyy").toFormatter();
TemporalAccessor ta = formatter.parse(node.textValue());
Instant instant = LocalDate.from(ta).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
Date d = Date.from(instant);
But it does not work since the day is missing.
What you have there is a YearMonth, not a LocalDate since the day is missing.
The following works:
String string = "October 2015";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM yyyy", Locale.ENGLISH);
YearMonth yearMonth = YearMonth.parse(string, formatter);
// Alternatively: YearMonth yearMonth = formatter.parse(string, YearMonth::from);
LocalDate date = yearMonth.atDay(1);
System.out.println(yearMonth); // prints "2015-10"
System.out.println(date); // prints "2015-10-01"
If you then want that as a java.util.Date, you need to specify which time zone you mean, maybe UTC or system default?
// ZoneId zone = ZoneOffset.UTC;
ZoneId zone = ZoneId.systemDefault();
Date javaUtilDate = Date.from(date.atStartOfDay(zone).toInstant());
System.out.println(javaUtilDate); // prints "Thu Oct 01 00:00:00 CEST 2015"
// because i'm in Europe/Stockholm.
How about this
DateFormat format = new SimpleDateFormat("MMMM yyyy", Locale.ENGLISH);
Date date = format.parse("October 2015");
System.out.println(date); // Prints Thu Oct 01 00:00:00 BST 2015
For java 8
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("MMMM yyyy")
.toFormatter(Locale.US);
TemporalAccessor ta = formatter.parse("October 2015");
YearMonth ym = YearMonth.from(ta);
LocalDateTime dt = LocalDateTime.of(ym.getYear(), ym.getMonthValue(),
1, 0, 0, 0);
Instant instant = Instant.from(dt.atZone(ZoneId.systemDefault()));
Date d = Date.from(instant);
You can use SimpleDateFormat's parse method for that
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("MMMMM yyyy"); //MMMM yyyy example: October 2015
public Date getDateFromString(String input) {
return DATE_FORMAT.parse(input);
}
For more information, see: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html#parse(java.lang.String,%20java.text.ParsePosition)
Explanation of format:
MMMM indicates you are parsing full name months such as "October"
yyyy indicates you have 4-digit length years. If you wanted to parse for example, October 15, your format would look like this: "MMMM yy"
Why not use a SimpleDateFormatter?
This works fine for me:
SimpleDateFormat formatter = new SimpleDateFormat("MMMM yyyy");
Date d = formatter.parse("Oktober 2015");

How to convert date strings from different TimeZones to Date object in one TimeZone

Im working on an RSS reader software. I get items with their pubDate (publish date) values as string, convert them to Date object, and put them to my DB. However, when I check my DB, I saw some interesting values such as the date of tomorrow.
I research this situation and found that it is about time zone value Z. For example when I get "Mon, 26 May 2014 21:24:29 -0500", it becomes "2014-05-27 05:24:29", the next day !
All I want is to get dates in any timezone and convert them to date in common timezone, such as my country's.
Here is my code :
public static String convert(String datestr) throws ParseException {
DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
Date date = formatter.parse(datestr);
SimpleDateFormat resultFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return resultFormatter.format(date);
}
And I use the method like that :
System.out.println(convert("Mon, 26 May 2014 21:24:29 -0500"));
The output is : 2014-05-27 05:24:29
Any idea ?
Since you haven't set a time zone, it's using your system's default.
Set a specific IANA time zone.
SimpleDateFormat resultFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
resultFormatter.setTimeZone(TimeZone.getTimeZone("America/New_York"));
return resultFormatter.format(date);
Looks like you passed a Date with timezone, but given a wrong format. If you are passing timezone like "-0500" you should rather use:
DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");
Remember that the system will always display the date using the current, default timezone (TimeZone.getDefault()) unless you override it by:
resultFormatter.setTimeZone(...)
This is working as expected. The date is converted as per your system's timezone.
Check the UTC offset of your system and replace it in the sample date string and look at the output.
For e.g: India is UTC+5:30
String datestr="Mon, 26 May 2014 21:24:29 +0530";
output:
2014-05-26 21:24:29
Alternate solution
If you don't want to consider the timezone of the input date string then simply truncate this information and remove zzz from pattern as well as shown in below code:
String datestr = "Mon, 26 May 2014 21:24:29 -0530";
datestr = datestr.replaceAll("\\s[-+](\\d+)$", ""); // truncate the timezone info if not needed
DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss"); // remove zzz from the pattern
Date date = formatter.parse(datestr);
SimpleDateFormat resultFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(resultFormatter.format(date));

Convert date to other format in JodaTime

I've a problem to convert a data in Java using Joda-Time library.
Pratically, the input date have this format:
Mon Apr 28 18:57:42 CEST 2014
I would like to see this output:
2014-04-28
I've tried this code, but doesn't works:
DateTimeFormatter dtf_out = DateTimeFormat.forPattern("yyyy-MM-dd");
DateTimeFormatter dtf_inp = DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss zzz yyyy");
String a = String.valueOf(dtf_inp.parseDateTime(String.valueOf(resultsJs.get(0).getTimestamp()))); //crash here
String b = String.valueOf(dtf_out.parseDateTime(a));
Note: resultsJs.get(0).getTimestamp() is a Date format.
Instead, this is the log:
...
Caused by: java.lang.IllegalArgumentException: Invalid format: "Mon Apr 28 18:57:42 CEST 2014"
at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:873)
...
You are trying to parse an epoch millisecond value, but you can only parse a String.
However, it seems you already have a millisecond value available, so only the formatting is required, which is via the print() method:
DateTimeFormatter dtf_out = DateTimeFormat.forPattern("yyyy-MM-dd");
String b = dtf_out.print(resultsJs.get(0).getTimestamp().getTime());
Its working fine after removing timezone info from the actual string but I have used time zone while parsing hence it will give you the correct result based on locale.
Please validate the result.
// pattern zzz is removed that is used for parsing time zone
DateTimeFormatter dtf_inp = DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss yyyy");
// time zone is added while parsing date time
DateTime dateTime = dtf_inp.withZone(DateTimeZone.forID("Europe/Paris"))
.parseDateTime("Mon Apr 28 18:57:42 2014");
// simply call toString(pattern) on DateTime
System.out.println(dateTime.toString("yyyy-MM-dd")); // 2014-04-28
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String output = sdf.format(yourDate);

Formatting Date from Date Object with only MM/DD/YYYY

Currently using Parse to obtain a date on an object by using:
Date date = object.getCreatedAt();
The returned String when displaying it in a TextView is this:
Mon Mar 17 22:39:27 CET 2014
However I really only want the MM/DD/YYYY to display like so: 3/17/2014
I've tried this:
Date date = object.getCreatedAt();
SimpleDateFormat originalFormat = new SimpleDateFormat("MMM DDD yyyy");
try {
Date originaldate = originalFormat.parse(date.toString());
finalDate = originaldate.toString();
} catch (java.text.ParseException e1) {
e1.printStackTrace();
}
but keep getting a ParseException for "Unparseable date", any idea what's going on? If I were to simply change this line back to this:
SimpleDateFormat originalFormat = new SimpleDateFormat("EEE MMM DDD HH:mm:ss z yyyy");
Then it prints out the full date again just fine with no parse exception, including all the date stuff I don't want.
Don't use parse method, use format instead :
Date date = object.getCreatedAt();
SimpleDateFormat formater = new SimpleDateFormat("M/d/yyyy");
String datestring = formater.format(date); // value is : 3/17/2014
http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#toString()
java.util.Date.toString() method always returns a String of format
dow mon dd hh:mm:ss zzz yyyy
For example, Thu Jan 10 02:00:00 EET 1992.
Your Date format "MMM DDD yyyy" expects a date String like Jan 10 1992 where 10 represents not 10th day of January but 10th day of year 1992.
Therefore to convert a date to String and convert it back to Date object using your format, you need to do
Date originaldate = originalFormat.parse(originalFormat.parse(date.toString()));
Or to convert Date.toString() to Date object,
SimpleDateFormat toStringFormat = new SimpleDateFormat("dow mon dd hh:mm:ss zzz yyyy");
Date originaldate = toStringFormat.parse(date.toString());
Lastly, if you want a Date string with format like 3/17/2014, the correct format is M/d/yyyy.
Refer to http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html for help on how to write Date format.

change date format to query database

how do I change date format of the following date
Thu May 17 00:00:00 GMT+05:30 2012
to
2012-05-17 00:00:00
I need it as date and not as string. I am using
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("")
But its not giving the result.
Actually I am storing the values date wise. So when someone enters the data for the same date again it should overwrite.
If I pass it as date object into the hibernate query it gives the result. But not always. ON few occasions it inserts again that is it inserts duplicate data for the same date. Befroe entering I am adding a method to check if data exists for that date. criteria.add(Restrictions.eq("date", date));
You shouldn't be doing string manipulation at all here. You've said in comments that it's a date/time field in the database, so why would there be any string conversion involved in your code?
Specify parameters in JDBC as java.sql.Date, java.sql.Timestamp or whatever - and then fetch them that way too. Don't do a string conversion. Ignore whatever format happens to be displayed when you query the database in a tool - don't think of the result as having a "format" at all - they're just dates.
String str ="Thu May 17 00:00:00 GMT+05:30 2012";
DateFormat old_format = new SimpleDateFormat("EEE MMM dd hh:mm:ss z yyyy");
Date newDate = null;
try {
newDate = old_format.parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
DateFormat new_format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = new_format.format(newDate);
System.out.println("==>"+date);
Do exactly as you do now but change parse("") to format(theDate)
theDate being the Date object you want to format
See
http://docs.oracle.com/javase/6/docs/api/java/text/DateFormat.html#format(java.util.Date)
String date = "Thu May 17 00:00:00 GMT+05:30 2012";
String oldFormat = "EEE MMM dd hh:mm:ss z yyyy";
String newFormat = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf1 = new SimpleDateFormat(oldFormat);
SimpleDateFormat sdf2 = new SimpleDateFormat(newFormat);
sdf2.format(sdf1.parse(date))

Categories

Resources