I want to set the fields of a given source date to a given target date using this method.
private static void setFields(final Date source,
final Date target,
final int ... fields)
{
final Calendar sourceCalendar = Calendar.getInstance();
sourceCalendar.setTime(source);
final Calendar targetCalendar = Calendar.getInstance();
targetCalendar.setTime(target);
for(int field : fields)
targetCalendar.set(field, sourceCalendar.get(field));
}
The minute of the target Date is not set.
How am I suppose to set it if I don't want to break the reference by using.
target = targetCalendar.getTime();
To change the target date to the value in the targetCalendar, use:
target.setTime(targetCalendar.getTime().getTime());
Assuming that's what you were asking, your question was a little unclear.
Related
I am creating a model where i'm trying to store gregorian calendar value in a column, but its showing me error, Calendar Datatype not supported by realmProxcy.
private String alarmName;
private Boolean alarmActive = true;
private Date alarmTime;
private String alarmTonePath = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM).toString();
private Boolean alarmVibrate = true;
private Calendar cal;
#PrimaryKey
public int alarmid;
Error:(30, 8) error: Type 'java.util.Calendar' of field 'cal' is not supported
how can i store this calendar value and fetch it
If you really need to store a Calendar instance, you can take advantage of it being a Serializable and the possibility of storing byte[] arrays in Realm objects - serialize your Calendar to byte array for storage and deserialize from byte array when accessing data.
Your object would look like this:
class MyRealmObject extends RealmObject {
private String alarmName;
private Boolean alarmActive = true;
private Date alarmTime;
private String alarmTonePath = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM).toString();
private Boolean alarmVibrate = true;
private byte[] serializedCalendar;
public Calendar getCalendar() {
return deserializeCalendar(serializedCalendar);
}
public void setCalendar(Calendar calendar) {
this.serializedCalendar = serializeCalendar(calendar);
}
}
Refer to this answer on Object<>byte[]serialization/deserialization on how to implement methods:
byte[] serializeCalendar(Calendar c);
Calendar deserializeCalendar(byte[] arr);
Realm database supports only Date class. You have to evaluate your Calendar instance to Date instance.
Calendar cal = Calendar.getInstance();
Date date = cal.getTime(); //save it to realm
From Realm documentation:
Realm supports the following field types: boolean, byte, short, int, long, float, double, String, Date and byte[]. The integer types byte, short, int, and long are all mapped to the same type (long actually) within Realm. Moreover, subclasses of RealmObject and RealmList are supported to model relationships.
https://realm.io/docs/java/latest/#field-types
Instead of Calendar, use Date from calendar.getTime(), if necessary store Calendar object converter to other type for save and read convert. Example:
public static Calendar toCalendarFromDate(Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal;
}
I am developing a multilingual Struts2 application, and I have quite a few actions which are dealing with Calendar properties. The default type conversion works most of the time, however in some locales I would like to change the default format used.
Specifically I would like to have the dates in English locale to follow the yyyy-MM-dd format. However, this does not work (strangely yyyy-MM-dd HH:mm works fine, but in this case I do not want to have a time part), as Struts2 expect dates in English locale to look different.
So, I would like to change the expected format of the conversion. I am looking for a sane solution for this. The options I have already tried:
A) Own StrutsTypeConverter. This should work, but I could not inject the format specified in the package.properties file into it.
B) Changing the getter/setter pair, to use String instead - works, but this is not a sane solution.
How to fix the solution A? Or is there an alternative approach? Of course, if this can be done entirely in configuration, that would be the best.
Okay, I found a solution for my problem at hand, still, I think this could done in a saner way. Anyway, I am posting my own type converter:
public class DateConverter extends StrutsTypeConverter {
private DateFormat dateFormat;
{
ActionContext ctx = ActionContext.getContext();
ActionSupport action = (ActionSupport) ctx.getActionInvocation().getAction();
String formatString = action.getText("dateformat.ui");
dateFormat = new SimpleDateFormat(formatString);
}
public Object convertFromString(Map context, String[] values, Class toClass) {
String input = values[0];
try {
Date date = dateFormat.parse(input);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal;
} catch (ParseException e) {
return null;
}
}
public String convertToString(Map context, Object object) {
Calendar cal = (Calendar) object;
return dateFormat.format(cal.getTime());
}
}
I removed the non-essential parts of the code, but this is a working solution.
I wonder why the setTime method behaves exactly like setDate, date without time, or instead to set the time on 2014-07-01 13:21:01 it is set on 2014-07-01 00:00:00 ?!?!
Is setTime deprecated?
Should I use setTimestamp???
Databases other than Oracle actually do distinguish between three different datatypes:
DATE only date, no time
TIME only time of the day, no date
TIMESTAMP both, date & time.
JDBC tries to abstract standard SQL concepts and the above three datatypes are defined by ANSI SQL and thus JDBC needs to support them.
As Oracle's date always includes the time, you have to use setTimestamp() otherwise the time is lost when you store it in the database.
setTime() Method :
The java.util.Calendar.setTime(Date) method sets Calendar's time with the given Date.
Following is the declaration for java.util.Calendar.setTime() method
public final void setTime(Date date)
This method does not return a value.
Example :
The following example shows the usage of java.util.calendar.setTime() method.
package com.tutorialspoint;
import java.util.*;
public class CalendarDemo {
public static void main(String[] args) {
// create a calendar
Calendar cal = Calendar.getInstance();
// get the current time
System.out.println("Current time is :" + cal.getTime());
// create new date and set it
Date date = new Date(95, 10, 10);
cal.setTime(date);
// print the new time
System.out.println("After setting Time: " + cal.getTime());
}
}
SetTimestamp Method :
Sets the designated parameter to the given timestamp and calendar values.
Syntax
public void setTimestamp(java.lang.String sCol,
java.sql.Timestamp x,
java.util.Calendar c)
Why does this code return 0001-02-05?
public static String getNowDate() throws ParseException
{
return Myformat(toFormattedDateString(Calendar.getInstance()));
}
I changed the code to:
public static String getNowDate() throws ParseException
{
Calendar temp=Calendar.getInstance();
return temp.YEAR+"-"+temp.MONTH+"-"+temp.DAY_OF_MONTH;
}
And now it returns 1-2-5.
Please, help me get the actual date. all i need is the Sdk date.
Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH are int constants (just look up in the API doc)...
So, as #Alex posted, to create a formatted String out of a Calendar instance, you should use SimpleDateFormat.
If however you need the numeric representations of specific fields, use the get(int) function:
int year = temp.get(Calendar.YEAR);
int month = temp.get(Calendar.MONTH);
int dayOfMonth = temp.get(Calendar.DAY_OF_MONTH);
WARNING! Month starts from 0!!! I've made some mistakes because of this!
Use SimpleDateFormat
new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime());
You are using constants to be used with the Calendar.get() method.
Why not use SimpleDateFormat?
public static String getNowDate() {
return new SimpleDateFormat("yyyy-MM-dd").format(new Date());
}
You are doing it wrong. Change to:
return temp.get(Calendar.YEAR)+"-"+ (temp.get(Calendar.MONTH)+1) +"-"+temp.get(Calendar.DAY_OF_MONTH);
Also, you may want to look into Date:
Date dt = new Date();
//this will get current date and time, guaranteed to nearest millisecond
System.out.println(dt.toString());
//you can format it as follows in your required format
System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(dt));
i want to use standard class called DateFormat which has subclass SimpleDateFormat TO write a method called convert which returns a String in the form dd.mm.yy: when passed a GregorianCalendar with a specific date
public String convert (Calendar gc) { ... }
For example, when myGC is a GregorianCalendar variable representing the 25th of December 2006, String s = convert(myGC); should set s to the string "25.12.06".
and i'm having trouble to write a convert method on this
public String convert(Calendar c) {
return new SimpleDateFormat("dd.MM.yy").format(c.getTime());
}
Eventually you'll want to store that SimpleDateFormat as a member (for example) if performance becomes a concern.
Why not just use a pattern like this one "dd.MM.yy" in your SimpleDateFormat ?
DateFormat dateFormatter = new SimpleDateFormat("dd.MM.yy");
String myDate = dateFormatter.format(cal.getTime());