Yaml file:
!!test.User
timestamp: 2012-11-22T01:02:03.567Z
Java class:
package test;
public class User {
public Date timestamp;
}
Parse it with snakeyaml:
String str = "2012-11-22T01:02:03.567Z";
// parse it manually
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse(str);
System.out.println("manually: " + date);
// parse it by snakeyaml
Yaml yaml = new Yaml();
yaml.setBeanAccess(BeanAccess.FIELD);
InputStream input = new FileInputStream("C:\\test.yaml");
User myUser = yaml.loadAs(input, User.class);
System.out.println("by Yaml: " + user.timestamp);
It prints:
manually: Thu Nov 22 01:02:03 CST 2012
by Yaml: Thu Nov 22 09:02:03 CST 2012
You can see they are different. Why?
Your manual method gets the time in the current time zone, but it is actually expressed in UTC (as indicated by the Z time zone). So actually the value parsed by Yaml seems to be the correct one.
I am puzzled about the actual value though, CST (Central Standard Time USA) should be 6 hours behind UTC, but you get 8 hours ahead.
Related
Here is the sample I am using.
import java.util.*;
import java.text.*;
public class TimeZoneTest
{
public static final String UTC_ZONE = "UTC";
static String utcDateString = "01/11/2016 11:00:00";
public static void main (String [] args)
{
DateFormat df;
try{
df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
System.out.println("Original Date : " + utcDateString);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = df.parse(utcDateString);
System.out.println(" In its Date format : " + date.toString());
System.out.println(" In its GMT format : " + date.toGMTString());
System.out.println(" In its Local format : " + date.toLocaleString());
}
catch (ParseException ex)
{
System.out.println("Exception!!!!");
}
}
}
Here is the output produced.
Original Date : 01/11/2016 11:00:00
In its Date format : Mon Jan 11 06:00:00 EST 2016
In its GMT format : 11 Jan 2016 11:00:00 GMT
In its Local format : Jan 11, 2016 6:00:00 AM
When using the time 11:00:00 and setting the TimeZone to UTC, I was expecting that the 11:00:00 which is my local time (Eastern) representation would then be converted to UTC which would produce 16:00:00.
Instead, it seems to take the string value 11:00:00 and process it as the UTC time instead of local time and return back my local time which is 06:00:00.
Is this the expected results?
When you set the timezone, is it supposed to convert the time being parsed (11:00:00 ) to that timezone and produce (16:00:00)?
OR
When you set the timezone, is it supposed to treat the time being parsed (11:00:00 ) as though it was in that timezone and return the local time (06:00:00)?
You're last statement is true: "OR When you set the timezone, is it supposed to treat the time being parsed (11:00:00 ) as though it was in that timezone and return the local time (06:00:00)?"
Basically, you set the timezone in the DateFormat, then you parse a date without timezone information, so it'll use the timezone from the DateFormat, to convert the String to certain amount of milliseconds from January 1, 1970. Then, you print that date with "toString" that will convert it back to String using your machine's timezone. But the date is the same throughout the program, just different format/timezone.
I am bit frustrated by this.
I have a String "2015-02-18T23:44:59" which represents time in GMT format.
I want to parse this date into date object.
String dateStr = "2015-02-18T23:44:59";
Date date = DateUtils.parseDate(dateStr, new String[]{"yyyy-MM-dd'T'HH:mm:ss"});
System.out.println(dateStr + " \t" + date.toString());
This outputs :
2015-02-18T23:44:59 Thu Feb 19 05:14:59 IST 2015
As you can see latter time has time zone IST but my original time was GMT.
I don't think there is any parse function which takes current date's time zone.
One way to answer is this question is that :
date.setTime(date.getTime() + ( date.getTimezoneOffset() * 60 * 1000));
System.out.println("\t" + date.toString());
This outputs:
Wed Feb 18 23:44:59 IST 2015
Which seems correct time (but incorrect time zone). Additionally, getTimezoneOffset() is deprecated.
Can anyone suggest me a better way to deal with String dates considering time zones.
I'd use a date format:
SimpleDateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = utcFormat.parse("2015-02-18T23:44:59");
I have three different times:
time on server - "Wed, 19 Feb 2014 11:44 CET"
time of start meeting on server - "12:00h"
time on device- "13:49"
I need to get time of start meeting on device ...this-> "14:00h" or time to meeting this-> "11m"
I'm trying to get it by using :
long ts = System.currentTimeMillis();
Date localTime = new Date(ts);
String gmt_time="12:00h";
SimpleDateFormat format = new SimpleDateFormat("HH:mm'h'");
format.setTimeZone(TimeZone.getTimeZone("GMT"));
Date d_date = null;
d_date = format.parse(gmt_time);
format.setTimeZone(TimeZone.getTimeZone("UTC"));
Date fromGmt = new Date(d_date.getTime() + TimeZone.getDefault().getOffset(localTime.getTime()));
String new_date=format.format(fromGmt);
But result in new_date is "15:00h" (I need "14:00h")
You assumption of CET = GMT on Wed, 19 Feb 2014 seems to be incorrect - refer to here.
CET is an hour ahead of GMT
11:44 CET would mean 10:44 GMT
Hence, when you calculate an offset from GMT time and your local time, it adds an hour to it.
Change format.setTimeZone(TimeZone.getTimeZone("GMT")); to format.setTimeZone(TimeZone.getTimeZone("CET")); and it should work as expected.
Found quickly solution
String cet_time="12.11.14"+" "+"12:00h";
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yy' 'HH:mm'h'");
format.setTimeZone(TimeZone.getTimeZone("CET"));
Date d_date = format.parse(cet_time);
( new SimpleDateFormat("dd.MM.yy")).format(fromGmt);//new date String
( new SimpleDateFormat("HH:mm'h'")).format(fromGmt);//new time String
I need to parse a string to a date but have no prior knowledge which pattern the string will be in. This is similar to the question How to convert String to Date without knowing the format?.
To solve this I adopted couple of patterns to test the outcome. However, what I am getting is a bit strange.
Example 1:
import java.util.Date;
import org.apache.commons.lang3.time.DateUtils;
public Date extractDate(String dateStr) {
String [] datePatterns = {"yyyy-MM-dd", "dd-MM-yyyy"};
Date date = null;
try {
date = DateUtils.parseDate(dateStr, datePatterns);
}
catch (Exception except) {
except.printStackTrace();
}
return date;
}
public static void main(String[] args) throws Exception {
System.out.println ("2013-09-30:" + extractDate("2013-09-30") );
System.out.println ("30-09-2013:" + extractDate("30-09-2013") );
}
This gives:
2013-10-30:Wed Oct 30 00:00:00 EAT 2013
30-09-2013:Mon Mar 05 00:00:00 EAT 36
The result from parsing '30-09-2013' is obviously strange.
Example 2: Here I only switch the pattern
String [] datePatterns = {"dd-MM-yyyy", "yyyy-MM-dd"};
This gives:
2013-10-30:Mon Mar 05 00:00:00 EAT 36
30-09-2013:Mon Sep 30 00:00:00 EAT 2013
In example 2 the result from parsing '2013-10-30' is strange.
How can one parse date strings using different formats/patterns so that the resulting dates are correct?
Update to use parseDateStrictly. When I did this I got the following output:
2013-09-30:Mon Sep 30 00:00:00 EDT 2013
30-09-2013:Mon Sep 30 00:00:00 EDT 2013
My answer would be same. Without any prior knowledge of the format you can't parse date.
Few examples of writing a date would be: DD-MM-YYYY, MM-DD-YYYY, DD/MM/YYYY, MM/DD/YYYY, MM/DD/YY, DD/MM/YY. For only these many types of dates can you find any common pattern?
NO! Without knowing the format which user enters you can't parse it.
If you come up with pattern matching, a date such as 10-09-2010 which matches with MM-DD-YYYY format and DD-MM-YYYY format too. Here you will have a problem
I need to work with dates and I wasn't sure how to go about that in Java since I have never done it before.
I am pulling dates from the Excel file and they can be retrieved in the Data format which would represent the date.
Ex:
2/1/2010
5/12/2011
8/15/2011
9/1/2011
9/1/2011
All my codes are pretty irrelvent to the question, but I am setting up a getter/setter method:
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
So my question is this, in what way when I am pulling the data from Excel:
temp.setDate((row.getCell(3).getDateCellValue());
I can set the limit so it only retrieves data from x amount of months. 8, 12, et.. from the last month/year displayed in the file, instead of going back all the way to 2010? I can provide more details if needed.
Edit: This is what I have now:
import java.util.Date;
Date date;
date = row.getCell(3).getDateCellValue();
It shows: Tue June 01 00:00:00
I don't care about Tuesday or 00:00:00, I just have a whole list of data and I only want to show x amount of months.
Edit: I figured it out. :)
The question is pretty vague, but if you are using Excel I have found it very beneficial to save the file as a 'filename.csv'. This format very easy to work with, it is comma delimited going across and newlines going down. If you are periodically checking the month, it would be easy to ensure that you only go x months backwards.
First you need to parse the dates accordingly using the SimpleDateFormat class. The result is a date object.
SimpleDateFormat df = new SimpleDateFormat( "M/d/yyyy" );
Date date = df.parse(row.getCell(3).getDateCellValue());
Then:
Calendar cal = Calendar.getInstance();
will return you an object ob type Calendar, where you can set the date by
cal.setTime(date);
Finally your loop reading the Excel file can determine according to the calendar object, if the date should be included / further processed by using:
int month = cal.get(Calendar.MONTH); // e.g. 11 for Nov
int year = cal.get(Calendar.YEAR); // e.g. 2011
You have to work with DateFormat.class fo parse the cell, or use a Calendar to put Day Month Year
EDIT
You can also use Calendar.class
final String[] tabDate = {"2/1/2010", "5/12/2011", "8/15/2011",
"9/1/2011", "9/1/2011"};
// Extract field's value
final Calendar c = Calendar.getInstance();
// Parse the list of stringDate
for (final String string : tabDate) {
System.out.println("Input string: " + string);
final String[] shortDate = string.split("/");
// Build Calendar
c.set(Integer.valueOf(shortDate[2]), Integer.valueOf(shortDate[0]),
Integer.valueOf(shortDate[1]));
// Extract date as you like
System.out.format("%25s : %d/%d/%d\t%s\n\n", c.getTime(),
c.get(Calendar.MONTH), c.get(Calendar.DATE),
c.get(Calendar.YEAR), c.getTimeInMillis());
}
Console :
Input string: 2/1/2010
Mon Mar 01 09:09:48 CET 2010 : 2/1/2010 1267430988109
Input string: 5/12/2011
Sun Jun 12 09:09:48 CEST 2011 : 5/12/2011 1307862588109
Input string: 8/15/2011
Thu Sep 15 09:09:48 CEST 2011 : 8/15/2011 1316070588109
Input string: 9/1/2011
Sat Oct 01 09:09:48 CEST 2011 : 9/1/2011 1317452988109
Input string: 9/1/2011
Sat Oct 01 09:09:48 CEST 2011 : 9/1/2011 1317452988109