After set the location, timezone can't convert - java

Below is my coding:
private final String TIME_ZONE_ID_TRKD_DEFAULT = "Etc/GMT";
private XMLGregorianCalendar getStartDateTime(boolean startFromZeroHour) {
XMLGregorianCalendar xmlCal = null;
try {
xmlCal = DatatypeFactory.newInstance().newXMLGregorianCalendar();
} catch (DatatypeConfigurationException e) {
e.printStackTrace();
}
Calendar now = Calendar.getInstance(TimeZone.getTimeZone("Asia/Singapore"));
now.setTimeZone(TimeZone.getTimeZone(TIME_ZONE_ID_TRKD_DEFAULT));
xmlCal.setDay(now.get(Calendar.DAY_OF_MONTH));
xmlCal.setMonth(now.get(Calendar.MONTH) + 1);
xmlCal.setYear(now.get(Calendar.YEAR));
xmlCal.setTime(now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE), now.get(Calendar.SECOND));
please kindly advice why it can't convert, and how should i do..

The code cannot be compiled because of an error on the line, where you get the instance of the calendar. I believe you wanted to do this (probably just copy/paste error?):
Calendar now = Calendar.getInstance(TimeZone.getTimeZone("Asia/Singapore"));

A better approach might be the following:
private final String TIME_ZONE_ID_TRKD_DEFAULT = "Etc/GMT";
private XMLGregorianCalendar getStartDateTime(boolean startFromZeroHour) {
XMLGregorianCalendar xmlCal = null;
try {
xmlCal = DatatypeFactory.newInstance().newXMLGregorianCalendar(new GregorianCalendar(TimeZone.getTimeZone(TIME_ZONE_ID_TRKD_DEFAULT)));
} catch (DatatypeConfigurationException e) {
e.printStackTrace();
}
xmlCal.setMillisecond(DatatypeConstants.FIELD_UNDEFINED);
xmlCal.setTimezone(DatatypeConstants.FIELD_UNDEFINED);
if(startFromZeroHour){
xmlCal.setHour(0);
}
return xmlCal;
}
public static void main(String[] args) {
Bug b = new Bug();
XMLGregorianCalendar startDateTime = b.getStartDateTime(true);
System.out.println(startDateTime);
XMLGregorianCalendar startDateTime2 = b.getStartDateTime(false);
System.out.println(startDateTime2);
}
First we create a GregorianCalendar instance using your timezone constant. It represents the current time (now) if the default constructor is used.
Then we use it to initialize the XMLGregorianCalendar.
You don't want to have the milliseconds and the timezone part, so we just unset them using DatatypeConstants.FIELD_UNDEFINED as stated in the JavaDoc https://docs.oracle.com/javase/7/docs/api/javax/xml/datatype/XMLGregorianCalendar.html#setMillisecond(int) .
I added a part setting the hour to zero if startFromZeroHour is set to true. It was not part of your code so you might want to remove or change it.

Related

Unparsable Date despite perfect format

I'm trying to parse a date departureTime:
String departureTime2, departureTime;
departureTime2 = departureTime = "2018-01-01 11:11:11.1";
Using the JUnit when method
when(bookingController.booking( departureTime, departureTime2).thenAnswer(new Answer<MockHttpSession>()
{
#Override
public MockHttpSession answer(InvocationOnMock invocation) throws Throwable
{
Object[] args = invocation.getArguments();
return (MockHttpSession) args[0];
}
});
My booking method in BookingController
#RequestMapping(value = "/bookingsingle", method = RequestMethod.POST)
public String bookingSingle(#RequestParam String departureTime,..)'
formats the date using
Date departureTimeAsDate = null;
DateFormat df = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss.S", Locale.ENGLISH);
try { departureTimeAsDate = df.parse(departureTime); } catch (ParseException e) { e.printStackTrace(); }
However I receive the error
java.text.ParseException: Unparseable date: "2018-01-01 11:11:11.1"
The date appears to be in the perfect format, and upon using the same code in a Java fiddle tool it compiles, however in intellij it runs into the error. Any suggestions would be appreciated.
EDIT:
I believe the problem may lie somewhere in the passing of the String in the when() method. Note that booking() has many irrelevant parameters I have excluded.

In Android Studio I am getting errors with Java.text.DateFormat

I am trying to change the following code, to be better used in an Android environment as part of an upcoming API.
public class DateFormatter implement JsonDeserializer<Date>,
JsonSerializer<Date> {
private final DateFormat[] formats;
public DateFormatter() {
formats = new DateFormat[3];
formats[0] = new SimpleDateFormat(DATE_FORMAT);
formats[1] = new SimpleDateFormat(DATE_FORMAT_V2_1);
formats[2] = new SimpleDateFormat(DATE_FORMAT_V2_2);
final TimeZone timeZone = TimeZone.getTimeZone("Zulu"); //$NON-NLS-1$
for (DateFormat format : formats)
format.setTimeZone(timeZone);
}
public Date deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
JsonParseException exception = null;
final String value = json.getAsString();
for (DateFormat format : formats)
try {
synchronized (format) {
return format.parse(value);
}
} catch (ParseException e) {
exception = new JsonParseException(e);
}
throw exception;
}
public JsonElement serialize(Date date, Type type,
JsonSerializationContext context) {
final DateFormat primary = formats[0];
String formatted;
synchronized (primary) {
formatted = primary.format(date);
}
return new JsonPrimitive(formatted);
}
}
I do not need to support v2.1 and v2.2. so I've been trying to remove the array, and code it for just a single instance. I'm running into some errors though.
Here is what I have so far:
class DateFormatter implements JsonDeserializer<Date>,
JsonSerializer<Date> {
private DateFormat formats;
DateFormatter() {
formats = new DateFormat;
formats = new SimpleDateFormat(String.valueOf(R.string.date_format), Locale.ENGLISH);
final TimeZone timeZone = TimeZone.getTimeZone("Zulu");
for (DateFormat format : formats)
format.setTimeZone(timeZone);
}
public Date deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
JsonParseException exception = null;
final String value;
value = json.getAsString();
for (DateFormat format : formats)
try {
synchronized (format) {
return format.parse(value);
}
} catch (ParseException e) {
exception = new JsonParseException(e);
}
throw exception;
}
public JsonElement serialize(Date date, Type type,
JsonSerializationContext context) {
final DateFormat primary;
primary = formats;
String formatted;
synchronized (primary) {
formatted = primary.format(date);
}
return new JsonPrimitive(formatted);
}
}
However, once I get it this point, I get errors. The main one I'm currently concerned about is getString.
What am I doing wrong here?
Edit:
#trooper I am not able to build the project, so I can't pull a --stacktrace --debug
I changed the 2nd code block in the post to reflect my current code. I changed;
formats = new SimpleDateFormat(getString(R.string.date_format), Locale.ENGLISH);
to;
formats = new SimpleDateFormat(String.valueOf(R.string.date_format), Locale.ENGLISH);
and that corrected my first question.
So, now that is answered, moving on to my next question. As you can see I'm moving from an array in the first block to a single instance in the second. the line
for (DateFormat format : formats)
the "formats' is throwing a "foreach not applicable to java.text.DateFormat'
I know foreach is used in arrays, what I don't know is how to remove that part of the loop and achieve what i need to... this is where I get really lost.
My end goal is to Convert the current GitHib APIv3 written in Java for the Eclipse Studio which supports API v2 & v3, over to an Android GitHub API v3, seeing as we won't need to cover v2.
I hope this edit is enough information to be able to answer.
Formats is not declared as an array. You need to declare this as an array an initialize it one by one.
try this,
private final DateFormat[] formats
formats = new DateFormat[3];
formats[0] = new SimpleDateFormat(getString(R.string.date_format), Locale.ENGLISH);
to remove the loop just use
formats = new DateFormat;
formats = new SimpleDateFormat(String.valueOf(R.string.date_format), Locale.ENGLISH);
final TimeZone timeZone = TimeZone.getTimeZone("Zulu");
formats.setTimeZone(timeZone);

How to use jXDatePicker with maskFormatter?

I would like to use a jxdatepicker with maskFormatter. I tried
MaskFormatter maskFormatter = new MaskFormatter ("##/##/####");
JFormattedTextField field=new JFormattedTextField (maskFormatter);
jXDatePicker.setEditor (field);
and
MaskFormatter maskFormatter = new MaskFormatter ("##/##/####");
maskFormatter.install (jXDatePicker.getEditor ());
neither the first nor the second solution worked
PS:
A JFormattedTextField work fine with MaskFormatter
AND jXDatePicker work fine with a simple JFormattedTextField
This is an old question, but seems to be still active, so here is how we implemented the functionality some time ago (swingx-all-1.6.5-1.jar):
1) Create a wrapper class for MaskFormatter
public class Wrapper extends MaskFormatter {
private final static String DD_MM_YYY = "dd/MM/yyyy";
public Wrapper(String string) throws ParseException {
super(string);
}
#Override
public Object stringToValue(String value) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat(DD_MM_YYY);
Date parsed = format.parse(value);
return parsed;
}
public String valueToString(Object value) throws ParseException {
if (value != null) {
SimpleDateFormat format = new SimpleDateFormat(DD_MM_YYY);
String formated = format.format((Date) value);
return super.valueToString(formated);
} else {
return super.valueToString(value);
}
}
}
2) Add the wrapped Formatter to the JFormattedTextField and set it on the JXDatePicker
MaskFormatter maskFormatter;
JXDatePicker datePicker = new JXDatePicker();
try {
maskFormatter = new Wrapper("##/##/####");
JFormattedTextField field = new JFormattedTextField(maskFormatter);
datePicker.setEditor(field);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
somePanel.add(datePicker);
The wrapper class basically does the formatting, since trying to set a DateFormat on the JXDatePicker led to various ParseException.
Personally I'm not very skilled in Java but after checking some docs quickly. I think setEditor is not the way to go. With maskFormatter.install you seem to go into the right direction. Something like this might help you out:
JXDatePicker picker = new JXDatePicker();
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
picker.setFormats(format);
Selective source: JXDatePicker using SimpleDateFormat to format dd.MM.yy to dd.MM.yyyy with current century
Or check out this: https://stackoverflow.com/a/9036979/4820655

Solrj Date request

How to request by date using SolrJ?
I get as a parameter a date in this format '01/10/2014'. Then I convert this format to a Date object and convert the object to a UTC format. Here is a code example of what I am doing :
public class DateHelper {
public static final String DD_MM_YYYY_FORMAT = "dd/MM/yyyy";
public static final String SOLR_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
public static Date getDateFromString(String date, String format) {
if (StringUtils.isNotEmpty(date)) {
try {
return FastDateFormat.getInstance(format).parse(date);
} catch (ParseException e) {
LOGGER.error(e.getMessage());
}
}
return null;
}
public static String getStringFromDate(Date date, String format) {
if (date != null) {
try {
return FastDateFormat.getInstance(format).format(date);
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
}
return "";
}
public static void main(String...args){
Date dateFromString = DateHelper.getDateFromString('01/10/2014', DateHelper.DD_MM_YYYY_FORMAT);
String date = DateHelper.getStringFromDate(dateFromString, DateHelper.SOLR_DATE_FORMAT);
System.out.println(date);
}
}
This small program displays '2014-10-01T00:00:00Z'. When I try to submit this date in Solr using a filter query, I receive this error from Sorl :
org.apache.solr.client.solrj.impl.HttpSolrServer$RemoteSolrException: Invalid Date String:'2014-10-01T00'
Here is my Solr query :
SolrQuery solrQuery = new SolrQuery("*:*");
String date = String.format( "date:%s",dateInput);
query.addFilterQuery(date);
getSolrServer().query(solrQuery, METHOD.POST);
How can I solve this problem? THx for your help.
P.S : The class FastDateFormat is from Apache Commons Lang 3. I am using solr version 4.8.1.
This happens because of the way filterQuery is created:
String date = String.format( "date:%s",dateInput);
query.addFilterQuery(date);
That way the solr gets:
date:2014-10-01T00:00:00Z
And the exception is thrown because of the multiple : symbols that the Query Parser cannot parse correctly.
In order to fix it the special characters that are part of Query Syntax should be escaped.
From the java side it can be done this way (using ClientUtils.escapeQueryChars from SolrJ):
String date = String.format( "date:%s", ClientUtils.escapeQueryChars(dateInput));
query.addFilterQuery(date);
Syntax to query solr date field -- Date:[YYYY-MM-DDTHH:mm:ssZ]

Java no response from other classes

I have this GUI program where I'm trying to basically copy windows CMD. Since I have lots of features in this program, I decided to put parts of the code in different classes. But it doesn't respond.
if(command.size()<2 && command.size()>0) {
switch(command.get(0)) {
case "dt":
getDateTime a = new getDateTime();
a.Start();
break;
// other case(s) down below
}
}
Here is the geDateTime class
public class getDateTime {
public static void Start() {
Terminal t = new Terminal();
try {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date();
String s = dateFormat.format(date).toString();
t.print(s);
}catch(Exception e){ e.printStackTrace(); }
}
}
Here is the print(); void in the main class...
public static void print(String s) {
Color c = Color.WHITE; // prints white text to JFrame
Style style = output.addStyle("Style", null);
StyleConstants.setForeground(style, c);
try{
document.insertString(document.getLength(), s, style);
}catch(Exception e){e.printStackTrace();}
}
Now when I enter the command for accessing the getDateTime class, the program freezes and I can't input anything. HOWEVER, if I just put the getDateTime class into a void inside the main class it works fine; but this would be a problem to just put everything into the main class since some function(s) could have hundreds of line of code.
No errors are produced when the program freezes.
In the code snippet that you have earlier, the code was trying to create a new Terminal rather than using the existing one.
Try this:
private static void print() {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date();
String s = dateFormat.format(date).toString();
print(s);
}
In the access method:
case "dt":
print();
break;
Update: On a side note, try to avoid static if at all possible. Generally speaking, it's bad practice. See https://stackoverflow.com/a/7026563/1216965

Categories

Resources