Not able to read the time from native calendar event - blackberry

I have created a appoitment for particular date and time in Blackberry calendar,i am trying to read date and time using the following code,but its showing the error.
private void getEvents() {
try {
EventList eventList = (EventList)PIM.getInstance().openPIMList(PIM.EVENT_LIST, PIM.READ_ONLY);
Enumeration events = eventList.items();
while (events.hasMoreElements()) {
Event event = (Event)events.nextElement();
if(eventList.isSupportedField(Event.ALARM) && event.countValues(Event.ALARM) > 0) {
long alarm = event.getDate(Event.ALARM, 0);
System.out.println(alarm);
}
}
}
i am not sure what is wrong in if loop

The field Event.ALARM contains:
Field specifying a relative time for an Alarm for this Event. Data for
this field is expressed with an INT data type. The alarm is expressed
in seconds and derived by subtracting the alarm value from every
date/time occurrence of this Event. For example, if this field has a
value of 600, then the alarm first occurs 600 seconds before the
date/time value specified by Event.START. For re-occurrences of the
event, the alarm is calculated by subtracting the stored value from
the date/time of the specific event occurrence.
So you need to get the value from the field Event.START for the Date/Time of the Event start. You can then subtract the value of Event.ALARM (as seconds) from the start Date/Time to get the time for any requested reminder.
long start = event.getDate(Event.START);
int alarm = event.getDate(Event.ALARM);
if (alarm > 0) {
long reminderTime = start - (long)alarm * 1000L;
...
}
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy HH:mm");
String dateString = sdf.formatLocal(start);

Related

Google Sheet -> Calendar -- Create Events with CalID

I have a giant spreadsheet to create student schedules. I've summarized all of the event information in one tab (see screenshot). The current Script I'm using creates a NEW calendar with the events. I just want it to add the events to an already pre-created calendar.
enter image description here
/**
* Creates a Google Calendar with events for each conference session in the
* spreadsheet, then writes the event IDs to the spreadsheet for future use.
* #param {Array<string[]>} values Cell values for the spreadsheet range.
* #param {Range} range A spreadsheet range that contains conference data.
*/
function setUpCalendar_(values, range) {
let cal = CalendarApp.createCalendar('Conference Calendar 2');
// Start at 1 to skip the header row.
for (let i = 1; i < values.length; i++) {
let session = values[i];
let title = session[0];
let start = joinDateAndTime_(session[1], session[3]);
let end = joinDateAndTime_(session[1], session[4]);
let options = {location: session[5], sendInvites: true};
let event = cal.createEvent(title, start, end, options)
.setGuestsCanSeeGuests(false);
session[6] = event.getId();
}
range.setValues(values);
// Stores the ID for the Calendar, which is needed to retrieve events by ID.
let scriptProperties = PropertiesService.getScriptProperties();
scriptProperties.setProperty('calId', cal.getId());
}
/**
* Creates a single Date object from separate date and time cells.
*
* #param {Date} date A Date object from which to extract the date.
* #param {Date} time A Date object from which to extract the time.
* #return {Date} A Date object representing the combined date and time.
*/
function joinDateAndTime_(date, time) {
date = new Date(date);
date.setHours(time.getHours());
date.setMinutes(time.getMinutes());
return date;
}
Try replacing the CalendarApp.createCalendar() call with CalendarApp.getCalendarById().

MT4 Expert Advisor EA issue with updating price for offline chart

The following script uses a timer and works well in normal charts to comment current candle closing price every 1 second on chart. However, on offline chart, it only loads the closing price once and does not update it every second. Here is the code:
void OnTimer()
{
int m=TimeSeconds(TimeLocal());
double CloseValue = Close[0]; //Current Candle Close Value
string CloseValueString = DoubleToString(CloseValue,5); //Current price
Comment(
"Current value :",CloseValueString,"\n",
"Candle time :",m
);
}
Solved by adding the Refreshrates() function which updates data for the offline chart at the end of my function:
void OnTimer()
{
int m=TimeSeconds(TimeLocal());
double CloseValue = Close[0]; //Current Candle Close Value
string CloseValueString = DoubleToString(CloseValue,5); //Current price
Comment(
"Current value :",CloseValueString,"\n",
"Candle time :",m
);
RefreshRates();
}

Flutter Timezone (as ZoneId)

I am relative new to Flutter. While I was experimenting, I came across with an issue. My REST Api takes a timezone parameter (Zone ID format such as Europe/London).
I saw both https://pub.dartlang.org/packages/flutter_native_timezone and https://pub.dartlang.org/packages/timezone, but neither of those serve my needs.
My goal is, when the user connect to the internet (without giving any location access to the app, if it is possible), get the timezone in ZoneId format and feed my back end in order to make the necessary date and time adjustments. Something similar to this
>>> var timezone = jstz.determine();
>>> timezone.name();
"Europe/London"
Presented in https://bitbucket.org/pellepim/jstimezonedetect
Any insights will be really helpful.
Thanks in advance
I've been also looking for this and here's what I found: https://pub.dev/packages/flutter_native_timezone
It a bit hacky under the hood, but it seems to work properly on both iOS and Android. Hope this will help someone in need.
Usage:
final String currentTimeZone = await FlutterNativeTimezone.getLocalTimezone();
print(currentTimeZone); // Europe/Moscow
Came up with a simple solution:
//server time(UTC)
String date_to_parse = "2019-06-23 12:59:43.444896+00:00";
DateTime server_datetime = DateTime.parse(date_to_parse);
//get current system local time
DateTime local_datetime = DateTime.now();
//get time diff
var timezoneOffset = local_datetime.timeZoneOffset;
var time_diff = new Duration(hours: timezoneOffset.inHours, minutes: timezoneOffset.inMinutes % 60);
//adjust the time diff
var new_local_time = server_datetime.add(time_diff);
After doing some digging, I found a (temporary) workaround to my issue.
Using
var now = new DateTime.now();
var timezoneOffset = now.timeZoneOffset;
I got the timezoneOffset in UTC format in flutter. Then send it to my back end as string (i.e. "-04") and drift my ZoneId properly.
Integer tzOffsetHour = Integer.valueOf(covertToTimezone);
ZoneOffset offset = ZoneOffset.ofHoursMinutes(tzOffsetHour, 0);
ZoneId zoneTZ = ZoneId.ofOffset("UTC", offset);
LocalDateTime localDateTimeClient = new Date().toInstant().atZone(zoneTZ).toLocalDateTime();
As a result I take the local time and date as stated in user's device, without using any location services, which was my goal from the beginning.
Until now, I have not faced any issues... we will see...
You can simply add .toLocal() to your DateTime object.
myDate = otherDate.toLocal();
myDate = DateTime.parse(json['server_date']).toLocal();
If you are just after the Time Zone offset. All you need is one line of code
int tzOffset = DateTime.now().timeZoneOffset.inHours;
The best way is to use timezone. as below
import 'package:timezone/data/latest.dart' as tz;
import 'package:timezone/timezone.dart' as tz;
String getNameLocalTimeZone() {
tz.initializeTimeZones();
var locations = tz.timeZoneDatabase.locations;
int milliseconds=DateTime.now().timeZoneOffset.inMilliseconds;
String name = "";
locations.forEach((key, value) {
for (var element in value.zones) {
if (element.offset == milliseconds) {
name = value.name;
break;
}
}
});
return name;
}
DateTime.now().timeZoneOffset // +5:30:00.000000 is expected format

Relative date parsing

How to parse relative datetime in GO?
Example of relative dates:
today at 9:17 AM
yesterday at 9:58 PM
Saturday at 9:44 PM
Wednesday at 11:01 AM
So format is DAY (in the past) at TIME. I tried next example:
const longForm = "Monday at 3:04 PM"
t, _ := time.Parse(longForm, "Saturday at 3:50 PM")
fmt.Println(t)
demo
Time is parsed correctly, but day/date is ignored...
Expanding on my comment:
Just Monday without further date reference is meaningless in the eyes of the parser, so it is discarded. Which Monday? The parser is strict, not fuzzy. Assuming Monday refers to the current week is not something that such a parser can do. You will not to write your own more sophisticated parser for that.
So it would have to be along these lines - one function that converts a relative fuzzy day to a real date, and replaces that in the original expression, and another one that parses the whole thing:
const dateFormat = "2006-01-02"
const longForm = "2006-01-02 at 3:04 PM"
func parseFuzzyDate(fuzzyTime string) (time.Time, error) {
formattedTime, err := parseDayAndReplaceIt(fuzzyTime)
if err != nil {
return nil, err
}
return time.Parse(longForm, formattedTime)
}
and the second function gets the fuzzy time, finds the day, parses it and returns. I'm not going to implement it, just write in comments what should be done:
func parseDayAndReplaceIt(fuzzyTime string) (string, error) {
// 1. Extract the day
// 2. Parse weekday names to relative time
// 3. if it's not a weekday name, parse things like "tomorrow" "yesterday"
// 4. replace the day string in the original fuzzyTime with a formatted date that the parser can understand
// 5. return the formatted date
}
I tweaked something that I wrote a while back and consolidated it into this example code:
func lastDateOf(targetDay time.Weekday, timeOfDay time.Time) time.Time {
const oneDay = 24 * time.Hour
var dayIndex time.Duration
//dayIndex -= oneDay
for {
if time.Now().Add(dayIndex).Weekday() == targetDay {
y, m, d := time.Now().Add(dayIndex).Date()
return timeOfDay.AddDate(y, int(m)-1, d-1)
}
dayIndex -= oneDay
}
}
It returns the date, relative to now, of the previous targetDay, added to timeOfDay, assuming that timeOfDay consists of hours, minutes and seconds, and the zero time values for year, month and day it will give you a suitable answer.
It's not very flexible but I believe it suits your example reasonably well. Although it doesn't address relative terms like "tomorrow", "yesterday" or "next Saturday".
runnable version in the playground.
Custom parser:
func RelativeDateParse(s string) (time.Time, error) {
for n := 0; n < 7; n++ {
day := time.Now().AddDate(0, 0, -n)
dayName := day.Format("Monday")
switch n {
case 0:
dayName = "today"
case 1:
dayName = "yesterday"
}
s = strings.Replace(s, dayName + " at", day.Format("2006-01-02"), -1)
}
return time.Parse("2006-01-02 3:04 PM", s)
}
demo

Unable to Select the month of a jquery datepicker using the Selenium

I am trying to select a custom date in the datepicker present in the jqueryui.com site, it is able to process the year , but the code that i written for the month is not working.Please find the code that i have used:-
private static void PickDate(WebDriver driver, String day, String mon, String year) throws Exception {
while (year != driver.findElement(By.cssSelector("span.ui-datepicker-year")).getText())
{
if (Integer.parseInt(year) < Integer.parseInt(driver.findElement(By.cssSelector("span.ui-datepicker-year")).getText()))
{
driver.findElement(By.cssSelector("a.ui-datepicker-prev")).click();
System.out.println(driver.findElement(By.cssSelector("span.ui-datepicker-month")).getText());
}
else if (Integer.parseInt(year) > Integer.parseInt(driver.findElement(By.cssSelector("span.ui-datepicker-year")).getText()))
{
driver.findElement(By.cssSelector("a.ui-datepicker-next")).click();
}
}
while (mon != (driver.findElement(By.cssSelector("span.ui-datepicker-month")).getText()))
{
if (driver.findElement(By.cssSelector("span.ui-datepicker-month")).getText() != "January")
{
driver.findElement(By.cssSelector("a.ui-datepicker-prev")).click();
}
if (mon != driver.findElement(By.cssSelector("span.ui-datepicker-month")).getText())
{
driver.findElement(By.cssSelector("a.ui-datepicker-next")).click();
}
}
If the purpose is to select a date in the datepicker, I would rather use execute script than click back and forth. :)
Something like:
((JavascriptExecutor) driver).ExecuteScript("$('#datepicker').datepicker('setDate', new Date(year, month, day))")
If you want to click on the previous/next button, then:
Because your code looks quite complicated, so I would like to provide another approach, which I believe that will be much simpler.
Notice that when you click on the previous/next button, it will move forward/backward by 1 month. So it's better if you firstly calculate how many months in difference between the date you want to select (month and year) and the current shown date on the DatePicker.
If you write in java, you can use something like:
YearMonth selectDate = YearMonth.of(year, month); // year, month are integer
int dp_Year = Integer.parseInt(driver.findElement(By.cssSelector("span.ui-datepicker-year")).getText());
int dp_Month = // convert it yourself
YearMonth dp_Date = YearMonth.of(dp_Year, dp_Month);
int month_diff = dp_Date.until(selectDate, ChronoUnit.MONTHS);
Based on month_diff and its sign (+ or -), you will know which button you need to click on and how many times.
I don't have java to try out, but I hope that the code above will work.

Resources