get previous date in J2ME - java-me

I want to get the date of previous month in J2ME.
I have found this code :
Calendar c = Calendar.getInstance();
c.add(Calendar.YEAR, -1); //one year back
c.add(Calendar.MONTH, -1);// then one month
but this is working in Java SE not J2ME, please if anyone can help me find the corresponding method or class in J2ME?

Calendar does not have method add.
c.set(Calendar.MONTH, -1)
Means you set value -1 at field MONTH.
Your solution is
// get current month
int m = c.get(Calendar.MONTH);
// decrement it
if (--m < 0) {
// if was january, must become december of past year
m = 11;
// set year to previous
c.set(Calendar.YEAR, c.get(Calendar.YEAR) - 1);
}
// set new value "m" to field MONTH
c.set(Calendar.MONTH, m);
Please refer to http://docs.oracle.com/javame/config/cldc/ref-impl/midp2.0/jsr118/index.html
for documentation. You should't work without it unless you know all you need.

Related

Error message "cannot find function getFullYear(...)" when entering date and trying to save the record

We are trying in a RESTLet to access the sublist "demandplandetail" from a NetSuite Item Demand Plan. Everything goes fine until a certain point. We are able to load it and process the demandplan for 2020. However, here it gets frustrating.
We know (can see from NetSuite) that there is data also for 2021. However, to access that from SuiteScript seems very difficult.
1st solution) The item demand plan has the field "year". OK, just set that to 2021, save and reload the record. Result: saving ignored, year still is 2020.
2nd solution) Set the year using a Date object as in:
var demandPlan = record.load(...)
var d = new Date();
demandPlan.setValue({
fieldId: 'year',
value: d
});
Gives the following:
:"TypeError: Cannot find function getFullYear in object NaN. (NLRecordScripting.scriptInit$lib#59)","stack":["setDatesForMonthAndYear(NLRecordScripting.scriptInit:108)","anonymous(N/serverRecordService)"
on saving the record. I also get the same using (various) strings adhering to acceptable date formats (as in '1/1/2021'). I have also tried the format package giving me a date string -> the same result.
Also read somewhere that you may need to set the start date (field 'startdate') in the record. Tried several variations but it stubbornly refuses :(.
Wonder if anyone has seen anything similar?
Best Regards,
Toni
Hi Please try the below code also check if you're passing date object to the field not the date string.
function formatDate() {
var dateROBD = format.parse({
value: new Date(),
type: format.Type.DATE
});
// this line optional if you want to try with or else ignore this
dateROBD = convertUTCDateToLocalDate(new Date(dateROBD));
return dateROBD;
}
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date.getTime() + date.getTimezoneOffset() * 60 * 1000);
var offset = date.getTimezoneOffset() / 60;
var hours = date.getHours();
newDate.setHours(hours - offset);
return newDate;
}
OK, mystery solved. Turned out that this is not supported in SuiteScript 2.0 but you need to use 1.0.

Comparing Time Strings in Swift

In the app I am making when the view loads I want an object to be deleted in the background whenever the current time is greater than the given time. Otherwise if the current time is less than the given time the object loads normally. This is working fine for any time within the hour for example if the current time is 9:30 PM and the given time is 9:45 PM it works fine, but if the current time is 9:30 PM and the given time is 11:45 PM for some reason it doesn't know how to compare the hour so it doesn't work. Here is my code:
if timeString > End {
self.SpotterMap.removeAnnotation(SpotAnnotation)
let endTime = End
let query:PFQuery = PFQuery(className: "SpotInfo")
query.whereKey("spotendtime", equalTo: endTime)
query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if let objects = objects {
for object in objects {
object.deleteInBackground()
}
}
})
print ("spot removed")
}
Can anyone give a solution to my problem?
Thanks
If you are going to work with times, you need to work with the NSDate type representation of your dates for the best accuracy, not a string one.
You will need to change your parse class spotInfo and add a column of type date, lets say you call it "realSpotEndTime".
To compare the times use .compare directly on the NSDates, if the dates return true when ordered ascending, it means that the first date comes before the second one. So your if statement would become;
(note: to get the real current time, you need to instantiate NSDate() right before comparison)
If this returns true and executes it means that the current time on the phone is less compared to the End time, remember, End needs to be in NSDate type as well, not string
let currentTime = NSDate()
//currentTime < End
if (currentTime.compare(End) == .OrderedAscending) {
...
query.whereKey("realSpotEndTime", lessThanOrEqualTo: currentTime)
}
or, alternatively you could do check if the current time is past the end time by
//End < currentTime
if (End.compare(currentTime) == .OrderedAscending) {
// fix parse query here
}

Recurring Events in SharePoint - Incorrect "Duration"

Background:
The company I work for has a regular SharePoint list with a custom ContentType (that does not inherit from a calendar list item) that it uses for Events. It then shows these using a calendar view. Seems simple enough.
We have the need to allow the user to choose a timezone for the event (different from their regional setting) that they are adding and to add the information to sharepoint such that it will show the correct time for each user looking at it world wide (based on their regional setting of course).
I added a list to SharePoint that is used to lookup SystemTimeZones (basically a SharePoint List representation of TimeZoneInfo.GetSystemTimeZones())
SPList timeZonesList = thisWeb.Lists.TryGetList("SystemTimeZones");
if(timeZonesList == null)
{
string title = "SystemTimeZones";
string description = "SharePoint List representation of TimeZoneInfo.GetSystemTimeZones() used for lookup.";
Guid newListId = thisWeb.Lists.Add(title, description, SPListTemplateType.GenericList);
timeZonesList = thisWeb.Lists.GetList(newListId, true);
timeZonesList.Fields.Add("SystemTimeZoneId", SPFieldType.Text, true);
timeZonesList.Fields.Add("SystemTimeZoneName", SPFieldType.Text, true);
SPView defaultTimeZonesView = timeZonesList.DefaultView;
defaultTimeZonesView.ViewFields.Add("SystemTimeZoneId");
defaultTimeZonesView.ViewFields.Add("SystemTimeZoneName");
defaultTimeZonesView.Update();
foreach (TimeZoneInfo timeZone in TimeZoneInfo.GetSystemTimeZones())
{
SPListItem temp = timeZonesList.AddItem();
temp["SystemTimeZoneId"] = timeZone.Id;
temp["SystemTimeZoneName"] = timeZone.DisplayName;
temp.Update();
}
}
I'm using this list for the lookup item for EventTimeZone in my custom add and edit forms for this list. The forms are direct copies of what SharePoint Designer would create (in that they are using the SharePoint:FormField's) they are just in Visual Studio bc I needed code-behind. I wanted to allow the users to see the events in their Regional TimeZone however when they edit them I wanted to show them in the TimeZone they were entered. (IE my regional timezone is Central so when I look at a Mountain meeting it will show me 10-11am but when I edit that same meeting it will say it is 9-10am). So on page load of edit I adjust the times:
SPListItem thisEvent = eventsList.GetItemById(savebutton1.ItemId);
if (thisEvent != null)
{
bool isAllDayEvent = false;
if (thisEvent["fAllDayEvent"] != null)
{
isAllDayEvent = (bool)thisEvent["fAllDayEvent"];
}
if (!isAllDayEvent)
{
SPFieldLookupValue lookupValue = new SPFieldLookupValue(thisEvent["Event Time Zone"].ToString());
TimeZoneInfo eventTimeZone = GetEventTimeZoneByListItemId(lookupValue.LookupId, rootWeb);
SPTimeZone regionalTimeZone = GetRegionalTimeZone(rootWeb);
DateTime regionalStartDateTime = Convert.ToDateTime(thisEvent["StartDate"]);
DateTime originalStartDateTime = TimeZoneInfo.ConvertTimeFromUtc(regionalTimeZone.LocalTimeToUTC(regionalStartDateTime), eventTimeZone);
ff3.ListItemFieldValue = originalStartDateTime;
DateTime regionalEndDateTime = Convert.ToDateTime(thisEvent["EndDate"]);
DateTime originalEndDateTime = TimeZoneInfo.ConvertTimeFromUtc(regionalTimeZone.LocalTimeToUTC(regionalEndDateTime), eventTimeZone);
ff4.ListItemFieldValue = originalEndDateTime;
}
else
{
// for some reason with all day events, sharepoint saves them
// as the previous day 6pm. but when they show up to any user
// they will show as 12am to 1159pm and show up correctly on the calendar
// HOWEVER, when it comes to edit, the start date isn't corrected on the
// form, so continuing to save without fixing it will continue to decrease
// the start date/time by one day
DateTime regionalStartDateTime = Convert.ToDateTime(thisEvent["StartDate"]);
ff3.ListItemFieldValue = regionalStartDateTime.AddDays(1);
}
All day events were strange but I was able to make it work by just writing test cases and see what happened (as you can see from my comments).
Then I tie into the list event receivers ItemAdded and ItemUpdated to "fix" the times since SharePoint is going to save them based on the user's regional setting and not the timezone the user chose. (Of course I'm slightly new to SharePoint -- not c# -- so I may have very much over complicated this, but I have been able to fine little documentation online). In the end I end up setting:
addedItem["StartDate"] = regionalTimeZone.UTCToLocalTime(correctedEventStart.ToUniversalTime());
addedItem["EndDate"] = regionalTimeZone.UTCToLocalTime(correctedEventEnd.ToUniversalTime()); TADA!! It saves and display perfectly! I was so excited! Until... I tried to save a recurring event. All of my recurring events save wonderfully, it's not the recurring part that's messed up. For some reason, after I change the StartDate and EndDate on a recurring event and call addedItem.Update() it is recalculating the "Duration" as if it is a single even instead of a recurring event. Example: I have an event that happens for a week daily from 9-10. When I first enter ItemAdded my Duration is 3600 (1 hour) as it should be bc Duration is treated differently for recurring events. However after I adjust the times and call Update() the duration spans the entire week :( If I manually set the Duration:
if (isRecurrence)
{
addedItem["Duration"] = (correctedEventEnd.TimeOfDay - correctedEventStart.TimeOfDay).TotalSeconds;
}
It still gets reset on Update(). So when you view the recurring item in a Calendar View the item spans the entire week instead of showing once a day.
I have all but pulled my hair out trying to figure this out. Any guidance would be wonderful. I understand Duration is a calculated field but I can't understand why calling listItem.Update() would ignore the fact that it is indeed properly marked as a recurring event and not calculate the Duration correctly. This honestly seems like a bug with SP 2010.
Thanks in advance!
**
EDIT: Additional info after comments below...
**
This SharePoint env has a server in pacific time and users across all US TimeZones, London, Tokyo, Abu Dabi, etc. Users in one timezone need to be able to create events in other timezones. Since nothing in the user's profile (for us anyway) will tell us what timezone they would like to see everything in, we added code to our master page to look at the local machine's timezone and always set their regional setting accordingly.
Example: I am in Nashville and I want to create an event that will happen in LA:
The data in ItemAdded shows that StartDate is what I entered 9am. So I'm creating a date that has PST at the end of it:
DateTime correctedEventStart = DateTime.Parse(addedItem["StartDate"] + " " + eventTimeZone.GetUtcOffset(DateTime.UtcNow).Hours + ":" + eventTimeZone.GetUtcOffset(DateTime.UtcNow).Minutes);
DateTime correctedEventEnd = DateTime.Parse(addedItem["EndDate"] + " " + eventTimeZone.GetUtcOffset(DateTime.UtcNow).Hours + ":" + eventTimeZone.GetUtcOffset(DateTime.UtcNow).Minutes);
Then to "trick" SharePoint I'm converting that PST time into the users regional time (so the user doesn't have to know anything about their regional setting nor do they have to think). So 9am PST is 7am CST (bc that's what SharePoint expects the time to be in since that's my regional setting). Here's the converstion from the correct time+timezone to the user regional timezone:
addedItem["StartDate"] = regionalTimeZone.UTCToLocalTime(correctedEventStart.ToUniversalTime());
addedItem["EndDate"] = regionalTimeZone.UTCToLocalTime(correctedEventEnd.ToUniversalTime());
I don't know if this makes sense to anyone outside of my world. But SharePoint obviously expects the times to be in the user's regional (or the web's) timezone. That's obvious my from unit testing. If there is an OOB way for me to allow a user in Central Time to create a meeting from 9-10am Pacific Time in a custom list I would LOVE to be able to use that. But I haven't been able to find anything.
Again, all of this works great... until you come to Recurring Events. And actually it works for recurring events until you try to view said event in a Calendar View. Then it looks like this:
Notice that "Recurring 8" is recurring the way it's supposed to, daily for 2 instances. However, the "span" or "duration" of the recurrence is 2 days rather than 1 hour. Where as "Recurring 15" shows correctly. The only difference in field values between the two when output to debug is the "Duration" field. Recurring 8 had it's start and end date's updated in ItemAdded and Recurring 15 went through ItemAdded but the ListItem.Update() was commented out. Per documentation SharePoint is supposed to calculate Duration differently for recurring items than it does for single items. The fact that the start and end dates are changed using the object model should not negate that.
Ok, so the way I ended up handling this is as follows. I decided to back out of the list event receiver because it really does appear to be a SharePoint bug in the recalculation of Duration for recurring events now working correctly. I opted to tie into the save event on the form and changing the values before they are even sent. This seems to work so far in all scenarios. All of my math is the same as before. So in my New2.aspx (new item form for this list)
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if ((SPContext.Current.FormContext.FormMode == SPControlMode.New) || (SPContext.Current.FormContext.FormMode == SPControlMode.Edit))
{
SPContext.Current.FormContext.OnSaveHandler += new EventHandler(SaveHandler);
}
}
protected void SaveHandler(object sender, EventArgs e)
{
Page.Validate();
if (Page.IsValid)
{
// fix times
SPFieldLookupValue lookupValue = new SPFieldLookupValue(ff5.Value.ToString());
TimeZoneInfo eventTimeZone = GetEventTimeZoneByListItemId(lookupValue.LookupId, SPContext.Current.Web);
SPTimeZone regionalTimeZone = GetRegionalTimeZone(SPContext.Current.Web);
bool isAllDayEvent = Convert.ToBoolean(ff6.Value);
bool isRecurrence = Convert.ToBoolean(ff11.Value);
DateTime correctedEventStart = DateTime.MinValue;
DateTime correctedEventEnd = DateTime.MinValue;
if (!isAllDayEvent && eventTimeZone != null && regionalTimeZone != null)
{
correctedEventStart = DateTime.Parse(ff3.Value.ToString() + " " + eventTimeZone.GetUtcOffset(DateTime.UtcNow).Hours + ":" + eventTimeZone.GetUtcOffset(DateTime.UtcNow).Minutes);
correctedEventEnd = DateTime.Parse(ff4.Value.ToString() + " " + eventTimeZone.GetUtcOffset(DateTime.UtcNow).Hours + ":" + eventTimeZone.GetUtcOffset(DateTime.UtcNow).Minutes);
ff3.ItemFieldValue = regionalTimeZone.UTCToLocalTime(correctedEventStart.ToUniversalTime());
ff4.ItemFieldValue = regionalTimeZone.UTCToLocalTime(correctedEventEnd.ToUniversalTime());
}
SPContext.Current.ListItem.Update();
}
}
This updates the times as my previous approach does but it will also calculate the duration correctly.
SharePoint handles displaying the correct time based on the user's regional settings (or web if the user hasn't set it) and displaying the correct times in calendar views. I did have to change the Edit form to have the correct values on edit:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
try
{
using (SPWeb rootWeb = SPContext.Current.Site.RootWeb)
{
SPList eventsList = rootWeb.Lists.TryGetList("Events");
if (eventsList != null)
{
SPListItem thisEvent = eventsList.GetItemById(savebutton1.ItemId);
if (thisEvent != null)
{
bool isAllDayEvent = false;
if (thisEvent["fAllDayEvent"] != null)
{
isAllDayEvent = (bool)thisEvent["fAllDayEvent"];
}
if (!isAllDayEvent)
{
SPFieldLookupValue lookupValue = new SPFieldLookupValue(thisEvent["Event Time Zone"].ToString());
TimeZoneInfo eventTimeZone = GetEventTimeZoneByListItemId(lookupValue.LookupId, rootWeb);
SPTimeZone regionalTimeZone = GetRegionalTimeZone(rootWeb);
DateTime regionalStartDateTime = Convert.ToDateTime(thisEvent["StartDate"]);
DateTime originalStartDateTime = TimeZoneInfo.ConvertTimeFromUtc(regionalTimeZone.LocalTimeToUTC(regionalStartDateTime), eventTimeZone);
ff3.ListItemFieldValue = originalStartDateTime;
DateTime regionalEndDateTime = Convert.ToDateTime(thisEvent["EndDate"]);
DateTime originalEndDateTime = TimeZoneInfo.ConvertTimeFromUtc(regionalTimeZone.LocalTimeToUTC(regionalEndDateTime), eventTimeZone);
ff4.ListItemFieldValue = originalEndDateTime;
}
else
{
// for some reason with all day events, sharepoint saves them
// as the previous day 6pm. but when they show up to any user
// they will show as 12am to 1159pm and show up correctly on the calendar
// HOWEVER, when it comes to edit, the start date isn't corrected on the
// form, so continuing to save without fixing it will continue to decrease
// the start date/time by one day
DateTime regionalStartDateTime = Convert.ToDateTime(thisEvent["StartDate"]);
ff3.ListItemFieldValue = regionalStartDateTime.AddDays(1);
}
}
}
}
}
catch (Exception ex)
{
DebugLogger.WriteLine(ex);
}
}
}
The Edit form has the same OnInit and SaveHandler as New.
I think you are running afoul of the shennagins that SharePoint uses for reccuring events. Essentially the events are stored in a single list item and expanded at query time. This makes the storage of events quite counter intuitive to how you expect.
From that post it looks like the EventDate and EndDate fields are used differently depending on the recurrence or not.
Also be aware the SharePoint stores dates in UTC 'under the hood' and converts back to the users (or websites) timezone on display. You may be able to use this knowledge to optimise some of the date logic.
More information
http://fatalfrenchy.wordpress.com/2010/07/16/sharepoint-recurrence-data-schema/
Share point 2010 ItemAdding insert Recurrence data on calendar
http://blog.tylerholmes.com/2012/02/how-sharepoint-deals-with-time-and-time.html
Here is the code I used to create an occuring event in another timezone (note: I did not explicitly set the duration)
public void AddRecurringItemGTM8Perth(SPList list)
{
string recData = "<recurrence><rule><firstDayOfWeek>su</firstDayOfWeek><repeat><daily dayFrequency=\"1\" /></repeat><windowEnd>2013-02-20T01:00:00Z</windowEnd></rule></recurrence>";
SPListItem newitem = list.Items.Add();
newitem["Title"] = "Perth " + DateTime.Now.ToString();
newitem["RecurrenceData"] = recData;
newitem["EventType"] = 1;
DateTime correctedEventStart = new DateTime(2013, 2, 3, 12, 0, 0);
//note that date is end of event and time is event end to calculate duration
DateTime correctedEventEnd = new DateTime(2013, 2, 20, 13, 0, 0);
SPTimeZone spTz = SPRegionalSettings.GlobalTimeZones[74]; //perth
correctedEventStart = spTz.LocalTimeToUTC(correctedEventStart);
correctedEventEnd = spTz.LocalTimeToUTC(correctedEventEnd);
correctedEventStart = list.ParentWeb.RegionalSettings.TimeZone.UTCToLocalTime(correctedEventStart);
correctedEventEnd = list.ParentWeb.RegionalSettings.TimeZone.UTCToLocalTime(correctedEventEnd);
newitem["Start Time"] = correctedEventStart;
newitem["End Time"] = correctedEventEnd;
newitem["Recurrence"] = true;
newitem["fAllDayEvent"] = false;
newitem["WorkspaceLink"] = false;
newitem["UID"] = Guid.NewGuid();
newitem.Update();
list.Update();
}
So I convert from users "local" to UTC and then back to the web local.
The UID is necessary or there is an error when you click on the event.
If you want a recurrence of 13 say... the code is:
string recData = "<recurrence><rule><firstDayOfWeek>su</firstDayOfWeek><repeat><daily dayFrequency=\"1\" /></repeat><repeatInstances>13</repeatInstances></rule></recurrence>";
DateTime correctedEventEnd = new DateTime(2013, 2, 3, 13, 0, 0).AddDays(13);
Whereas no end date is :
string recData = "<recurrence><rule><firstDayOfWeek>su</firstDayOfWeek><repeat><daily dayFrequency=\"1\" /></repeat><repeatForever>FALSE</repeatForever></rule></recurrence>";
DateTime correctedEventEnd = new DateTime(2013, 2, 3, 13, 0, 0).AddDays(998);
It might be quite old, but my answer may help someone.
You just have to explicitly put EventType = 1 in update as well.

SharePoint 2010 - Need suggestion

I have one datasheet like mentioned below
WorkWeek Person1 Person2
WW1 X Y
WW2 Z A
WW3 X Z
Where A,X,Y & Z are members of the sharepoint group.
Required I want display a webpart like this
WW1
Image1 Image2
X Y
Next Week the webpart should get updated like this dynamically.
WW2
Image3 Image4
Z A
Where this requirement is possible, If possible then pls suggest how to accomplish this.
I can provide you some Logic which may help you to accomplish this requirement.
Create one Visual web part with the user control which has html as per your requirement,
To get the data from the datasheet use the Code to read the data from Data sheet
When you want to display the data for the First week create one varible and maintain it to identify the sequence of week to get from datasheet.
First time When you access the datasheet set this varibale with your week of year number.
Condition the reading of datasheet with this variable like IF variable is null then assign it the week no of year.,
Check this variable next time you come to this logic that If variable is less than the week no current week no of year then take datasheet last you get + 1 means Datasheet 2 and so on
..
Sorry for bad english
variable : one for DaasheetNo, WeekNo,CurrentWeekNo
assign datasheetNo = Sheet1
If(WeekNo== Null)
{
first time getdata from DaasheetNo (First Sheet)
}
else if(WeekNo < CurrentWeekNo)
{
Get data from datasheetNo +1
}
Hope it helps you
This is called weekly update Webpart in SharePoint.
My Idea:
you can set one CurrentDate value like DateTime.Today to Current Web properties.also set one more properties which WorkWeek users. now check
SPWeb web = SPContext.Current.Web;
if (string.isnullorEmpty(web.Properties["CurrentDate"]))
{
web.Properties["CurrentDate"] = DateTime.Today.Tostring();
// do the stuff for displying data.
}
else
{
if(IFChangeNeeded())
{
// do the stuff for displying data.
}
else
{
web.Properties["CurrentDate"] = DateTime.Today.Tostring();
// do the stuff for displying data.
}
}
IfChangeNeeded() is function which return bool value. this function check that employee need to change on this week.
public bool IFChangeNeeded()
{
DateTime PropDate = Convert.ToDateTime(web.Properties["CurrentDate"]);
DateTime TDate = DateTime.Today;
if(WeekNo(TDate) == WeekNo(PropDate)) // WeekNo is function return weekno from current date.
{
return true;
}
else
{
return false;
}
}

Strange FormatException after upgrading in VS 2010

I get this FormatException after i upgraded to VS 2010. Not anything really special.
Code:
private void ManageDateEditControls()
{
apoDateEdit.DateTime = DateTime.Parse(string.Format("01/{0}/{1}", DateTime.Now.Month-1, DateTime.Now.Year));
eosDateEdit.DateTime = DateTime.Parse(string.Format("{0}/{1}/{2}", GetLastDayOfMonth(DateTime.Now.Month + 1),
DateTime.Now.Month - 1, DateTime.Now.Year)); <-- FormatException occurs in this line.
}
private static int GetLastDayOfMonth(int month)
{
// set return value to the last day of the month
// for any date passed in to the method
// create a datetime variable set to the passed in date
DateTime dtTo = new DateTime(DateTime.Now.Year, month, 1);
// overshoot the date by a month
dtTo = dtTo.AddMonths(1);
// remove all of the days in the next month
// to get bumped down to the last day of the
// previous month
dtTo = dtTo.AddDays(-(dtTo.Day));
// return the last day of the month
return dtTo.Day;
}
Lets say you get now if you run this 31/6/2010. I think its a valid date.
I have tested the date that is generated and its ok...this project never had this problem while was working in VS 2008.
Any ideas?
Your FormatException is caused by passing 31/6/2010 as an argument to DateTime.Parse(). 31/6/2010 is not a valid date - there are only 30 days in June.
If you need the last day in any month, you would be better off using the DateTime.DaysInMonth() method. It takes both the month and year as arguments so it can deal with leap years.

Resources