java Calendar Timezones strange stuff - java

I have been playing with calendar, timezones, and conversion since yesterday. This thing has got me all confused. Here is my code:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
class Dates {
public static void main(String[] args) {
test1();
test2();
}
private static void test1() {
String dateString = "2013-10-06T16:25";
String pattern = "yyyy-MM-dd'T'HH:mm";
SimpleDateFormat dtf = new SimpleDateFormat(pattern);
long mil;
Date date;
try {
date = dtf.parse(dateString);
mil = date.getTime();
System.out.println("Create date:" + date);
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(mil);
System.out.println ("millis:"+ mil);
printCal ("Default Cal:", cal);
} catch (ParseException ex) {
Logger.getLogger(Dates.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static void test2() {
// TODO Auto-generated method stub
long ms = 1381091100000L;
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Americas/New_York"));
cal.setTimeInMillis(ms);
printCal ("EST: ", cal);
}
private static void printCal(String str, Calendar cal) {
// TODO Auto-generated method stub
System.out.println(str+"Year:" + cal.get(Calendar.YEAR) + ", Month:"
+ cal.get(Calendar.MONTH) + ", Date:"
+ cal.get(Calendar.DATE) + ", Hour:"
+ cal.get(Calendar.HOUR) + ", Minutes:"
+ cal.get(Calendar.MINUTE) + ", Seconds:"
+ cal.get(Calendar.SECOND) + ", AM_PM: +"+ cal.get(Calendar.AM));
}
}
The output:
Create date:Sun Oct 06 16:25:00 EDT 2013
millis:1381091100000
Default Cal:Year:2013, Month:9, Date:6, Hour:4, Minutes:25, Seconds:0, AM_PM: +1
EST: Year:2013, Month:9, Date:6, Hour:8, Minutes:25, Seconds:0, AM_PM: +1
As you can see, I am using the same millis in test2() that I get from the test1(). The Hour in test 1 is the expected 4 while in test2 it is 8! What is causing this problem?
Thanks.

Your "Default Cal" prints time in your local timezone: EDT (-4)
Your "EST" calendar prints time in UTC/GMT timezone, because "Americas/New_York" is incorrect (extra "s"), it should be "America/New_York", since it's incorrect, TimeZone.getTimeZone(...) returns UTC

Related

How to fix "ParseException cannot be resolved to a type"?

I have a code which is shown as follows. But it has error, which is indicated as "error line". The error message is:
java.lang.NoClassDefFoundError: ParseException.
Can anyone help me fix the error? Thank you so much!
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.*;
public class TestCalendar2 {
public static void main(String[] args) throws ParseException{ // error line
String str = "2020-10-10";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("df:" + df);
Date date = df.parse(str);
System.out.println("date:" + date);
Calendar c = new GregorianCalendar();
System.out.println("c:" + c);
c.setTime(date);
System.out.println("Sunday\t一\t二\t三\t四\t五\t六");
c.set(Calendar.DAY_OF_MONTH,1);
for(int i = 0; i < c.get(Calendar.DAY_OF_WEEK)-1;i++) {
System.out.print("\t");
}
for (int i=1; i<=c.getActualMaximum(Calendar.DATE); i++) {
System.out.print(c.get(Calendar.DAY_OF_MONTH)+"\t");
if(c.get(Calendar.DAY_OF_WEEK)== Calendar.SATURDAY) {
System.out.println();
}
c.add(Calendar.DAY_OF_MONTH, 1);
}
}
}
You need import it:
import java.text.ParseException;

Get first element of ResultTable[] in java

These codes:
String genType = FileConstants.CHANGE_CYCLE;
ResultTable[] genericCode = RTManager.getRTCsmGenericCodesDecodeList(genType);
String genCode = Arrays.toString(genericCode);
Returns these values:
genCode = [[code=22:00:00]
[dCode=Cut-off time for change bill_cycle if existing cycle_close_date=activity_date]]
Question: how do i get only '22:00:00' and convert it as Time datatype?
If the item in the ResultTable array has a toString() and it produces string then you can get it like this.
genericCode[0].toString().split("=")[1]
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateExample {
public static void main(String[] args) {
String time = "22:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
Date date;
try {
date = sdf.parse(time);
System.out.println("Time: " + sdf.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
}
}

Formatting XMLGregorianCalendar

I want to convert a string that contains a date to a GregorianCalendar in the form "dd.mm.yyyy".
I have used the below code. I am able to convert to the desired datatype, but not in the desired format.
Any suggestions regarding this would be helpful to me.
public class StringToCalander {
public static void main(String args[]) throws DatatypeConfigurationException {
String date="20160916";
Date dob=null;
DateFormat df=new SimpleDateFormat("yyyyMMdd");
try {
dob=df.parse( date );
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(dob);
XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
System.out.println(" xml date value is:"+xmlDate);
//output is 2016-09-16T00:00:00.000+02:00
//but i need output in the format dd.mm.yyyy(16.09.2016)
}
}
Try this. (updated for GregorianCalendar as well)
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
public class StringToCalendar {
public static void main(String args[])
throws DatatypeConfigurationException {
String FORMATER = "ddMMyyyy";
DateFormat format = new SimpleDateFormat(FORMATER);
Date date2 = new Date();
XMLGregorianCalendar gDateFormatted = DatatypeFactory.newInstance()
.newXMLGregorianCalendar(format.format(date2));
System.out.println("xmlDate via GregorianCalendar: " + gDateFormatted);
}
}
You can use a Date-Object to format your XMLGregorianCalendar:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
public class Main {
public static void main(String args[])
throws DatatypeConfigurationException {
String format = "dd'.'MM'.'yyyy";
DateFormat formatter = new SimpleDateFormat(format);
GregorianCalendar date = new GregorianCalendar();
XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance()
.newXMLGregorianCalendar(date);
Date dateObject = xmlDate.toGregorianCalendar().getTime();
System.out.println("xml date value is: " + formatter.format(dateObject));
}
}

Convert String to Timestamp Java

So I am having this issue that I can't wrap my head around. I've read similar questions posed but very case I've found there is an issue with the format, and my format is correct.
Basically I am trying to convert a String into a Timestamp, and I get the unparseable date error.
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Hello {
public static Timestamp convertStringToTimestamp(String str_date) {
try {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS");
Date date = formatter.parse(str_date);
java.sql.Timestamp timeStampDate = new Timestamp(date.getTime());
return timeStampDate;
} catch (ParseException e) {
System.out.println("Exception :" + e);
return null;
}
}
public static void main(String[] args) {
Timestamp ts = convertStringToTimestamp("2015-06-09 11:51:12,708");
Timestamp ts2 = convertStringToTimestamp("2015-04-17 11:29:49.564");
System.out.println(ts +" | "+ts2);
}
}
Output:
Exception :java.text.ParseException: Unparseable date: "2015-06-09 11:51:12,708"
Exception :java.text.ParseException: Unparseable date: "2015-04-17 11:29:49.564"
null | null
Any ideas?
This works perfectly to me.
I just passed the right pattern as an input as well.
public static Timestamp convertStringToTimestamp(String str_date, String pattern) {
try {
SimpleDateFormat formatter = new SimpleDateFormat(pattern);
Date date = formatter.parse(str_date);
java.sql.Timestamp timeStampDate = new Timestamp(date.getTime());
return timeStampDate;
} catch (ParseException e) {
System.out.println("Exception :" + e);
return null;
}
}
public static void main(String[] args) {
Timestamp ts = convertStringToTimestamp("2015-06-09 11:51:12,708", "yyyy-MM-dd HH:mm:ss,SSS");
Timestamp ts2 = convertStringToTimestamp("2015-04-17 11:29:49.564", "yyyy-MM-dd HH:mm:ss.SSS");
System.out.println(ts +" | "+ts2);
}
The output is:
2015-06-09 11:51:12.708 | 2015-04-17 11:29:49.564
"2015-06-09 11:51:12,708" is working for me but "2015-04-17 11:29:49.564" won't. You specified the regex for "," so "." would not. It is perfectly normal.
you need to fix the comma
Timestamp ts2 = convertStringToTimestamp("2015-04-17 11:29:49.564");
**Update**
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SomeClass {
public static void main(String[] args) {
System.out.println(convertStringToTimestamp("2015-06-09 11:51:12,708"));
//be consistent here with , and .
System.out.println(convertStringToTimestamp("2015-04-17 11:29:49.564"));
System.out.println();
}
private static Timestamp convertStringToTimestamp(String something) {
SimpleDateFormat dateFormat = null;
if(something.contains(".")) {
dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
}
if(something.contains(",")) {
dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss,SSS");
}
Timestamp timestamp = null;
Date parsedDate;
try {
parsedDate = dateFormat.parse(something);
timestamp = new java.sql.Timestamp(parsedDate.getTime());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return timestamp;
}
}

SimpleDateFormat not producing expected output

I have used JCalender to get the date. It returned the date like this
Thu Mar 01 18:35:53 PST 2012
But what I need is this format.
01/03/2012
I have tried the following code:
SimpleDateFormat MydateFormat = new SimpleDateFormat("dd/MM/yyyy");
FromDate.getDateEditor().addPropertyChangeListener(
new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent e) {
if ("date".equals(e.getPropertyName())) {
System.out.println(e.getPropertyName()
+ ": -->" + (Date) e.getNewValue());
try {
fdate = MydateFormat.parse(e.getNewValue().toString());
JOptionPane.showMessageDialog(rootPane, fdate);
} catch (ParseException ex) {
Logger.getLogger(DashboardChart.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
What you were asking for was a new Date object based on the current one. Try this:
package test;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JOptionPane;
public class TestDateFormat {
public static void main(String[] args) {
SimpleDateFormat MydateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
String fdate = MydateFormat.format(date);
System.out.println(date + " \tFORMATTED: " + fdate);
JOptionPane.showMessageDialog(null, fdate);
}
}
E.G. Output
Sat Mar 24 23:40:09 EST 2012 FORMATTED: 24/03/2012

Categories