GetDateTime() public method

public GetDateTime ( ) : DateTime
return DateTime
        /// <summary>
        /// This is the click handler for the 'Get Activity History' button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        async private void ScenarioGetActivityHistory(object sender, RoutedEventArgs e)
        {
            // Reset fields and status
            ScenarioOutput_Count.Text = "No data";
            ScenarioOutput_Activity1.Text = "No data";
            ScenarioOutput_Confidence1.Text = "No data";
            ScenarioOutput_Timestamp1.Text = "No data";
            ScenarioOutput_ActivityN.Text = "No data";
            ScenarioOutput_ConfidenceN.Text = "No data";
            ScenarioOutput_TimestampN.Text = "No data";
            rootPage.NotifyUser("", NotifyType.StatusMessage);

            var calendar = new Calendar();
            calendar.SetToNow();
            calendar.AddDays(-1);
            var yesterday = calendar.GetDateTime();

            // Get history from yesterday onwards
            var history = await ActivitySensor.GetSystemHistoryAsync(yesterday);

            ScenarioOutput_Count.Text = history.Count.ToString();
            if (history.Count > 0)
            {
                var reading1 = history[0];
                ScenarioOutput_Activity1.Text = reading1.Activity.ToString();
                ScenarioOutput_Confidence1.Text = reading1.Confidence.ToString();
                ScenarioOutput_Timestamp1.Text = reading1.Timestamp.ToString("u");

                var readingN = history[history.Count - 1];
                ScenarioOutput_ActivityN.Text = readingN.Activity.ToString();
                ScenarioOutput_ConfidenceN.Text = readingN.Confidence.ToString();
                ScenarioOutput_TimestampN.Text = readingN.Timestamp.ToString("u");
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Coerces the <paramref name="utcDateTime"/> according to the min and max
        /// allowed values of the <paramref name="calendar"/> parameter.
        /// </summary>
        /// <returns>The coerced value.</returns>
        internal static DateTime CoerceDateTime(DateTime utcDateTime, Windows.Globalization.Calendar calendar)
        {
            var calendarValue = calendar.GetDateTime().UtcDateTime;
            var dateTime      = DateTime.SpecifyKind(utcDateTime, DateTimeKind.Utc);

            calendar.SetToMin();
            calendar.AddDays(1);
            var minValue = calendar.GetDateTime().UtcDateTime.AddDays(-1);

            calendar.SetToMax();
            calendar.AddDays(-1);
            var maxValue = calendar.GetDateTime().UtcDateTime.AddDays(1);

            calendar.SetDateTime(calendarValue);

            if (dateTime < minValue)
            {
                return(DateTime.SpecifyKind(minValue, utcDateTime.Kind));
            }

            if (dateTime > maxValue)
            {
                return(DateTime.SpecifyKind(maxValue, utcDateTime.Kind));
            }

            return(utcDateTime);
        }
Exemplo n.º 3
0
 private static DateTime InitRepeatStartDate(String repeatFrom, DateTime completedTime, DateTime dueDate, Calendar taskCal)
 {
     if (IsRepeatFromCompleteTime(repeatFrom, completedTime))
     {
         taskCal.Year = completedTime.Year;
         taskCal.Month = completedTime.Month;
         taskCal.Day = completedTime.Day;
         taskCal.Hour = dueDate.Hour;
         taskCal.Minute = dueDate.Minute;
         taskCal.Second = dueDate.Second;
         return taskCal.GetDateTime().DateTime;
         //taskCal.SetDateTime(completedTime);//.setTime(completedTime);
         //int year = taskCal.Year;//taskCal.get(Calendar.YEAR);
         //int month = taskCal.Month;//.get(Calendar.MONTH);
         //int day = taskCal.Day;//.get(Calendar.DAY_OF_MONTH);
         //taskCal.SetDateTime(dueDate)//.setTime(dueDate);
         //int hour = taskCal.Hour;//.get(Calendar.HOUR_OF_DAY);
         //int minute = taskCal.Minute;//.get(Calendar.MINUTE);
         //int second = taskCal.Second;//.get(Calendar.SECOND);
         //taskCal.clear();
         //taskCal.(year, month, day, hour, minute, second);
         //return taskCal.getTime();
     }
     return dueDate;
 }
Exemplo n.º 4
0
 public static DateTime? CalculateRemindTime(TickTickDuration duration, long dueTime)
 {
     if (dueTime <= 0 || duration == null)
     {
         return null;
     }
     Calendar calendar = new Calendar();
     //calendar.setTimeInMillis(dueTime); // TODO 有问题
     duration.AddDurationToDate(calendar);
     return DateTimeUtils.ClearSecondOfDay(calendar.GetDateTime().DateTime).Value;
 }
Exemplo n.º 5
0
        /// <summary>
        /// Gets the UTC <see cref="DateTime"/> of the calendar.
        /// </summary>
        internal static DateTime GetUtcDateTime(this Windows.Globalization.Calendar calendar)
        {
            DateTime dateTime;

            if (calendar.Year == calendar.LastYearInThisEra)
            {
                calendar.AddYears(-1);
                dateTime = calendar.GetDateTime().UtcDateTime;
                if (dateTime > DateTime.MaxValue.AddYears(-1))
                {
                    dateTime = DateTime.MaxValue;
                }
                else
                {
                    dateTime = dateTime.AddYears(1);
                }

                calendar.AddYears(1);
            }
            else if (calendar.Year == calendar.FirstYearInThisEra)
            {
                calendar.AddYears(1);
                dateTime = calendar.GetDateTime().UtcDateTime;
                if (dateTime < DateTime.MinValue.AddYears(1))
                {
                    dateTime = DateTime.MinValue;
                }
                else
                {
                    dateTime = dateTime.AddYears(-1);
                }

                calendar.AddYears(-1);
            }
            else
            {
                dateTime = calendar.GetDateTime().UtcDateTime;
            }

            return(dateTime);
        }
        /// <summary>
        /// This is the click handler for the 'Get Activity History' button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        async private void ScenarioGetActivityHistory(object sender, RoutedEventArgs e)
        {
            // Reset fields and status
            ScenarioOutput_Count.Text = "No data";
            ScenarioOutput_Activity1.Text = "No data";
            ScenarioOutput_Confidence1.Text = "No data";
            ScenarioOutput_Timestamp1.Text = "No data";
            ScenarioOutput_ActivityN.Text = "No data";
            ScenarioOutput_ConfidenceN.Text = "No data";
            ScenarioOutput_TimestampN.Text = "No data";
            rootPage.NotifyUser("", NotifyType.StatusMessage);

            // Determine if we can access activity sensors
            var deviceAccessInfo = DeviceAccessInformation.CreateFromDeviceClassId(ActivitySensorClassId);
            if (deviceAccessInfo.CurrentStatus == DeviceAccessStatus.Allowed)
            {
                // Determine if an activity sensor is present
                // This can also be done using Windows::Devices::Enumeration::DeviceInformation::FindAllAsync
                var activitySensor = await ActivitySensor.GetDefaultAsync();
                if (activitySensor != null)
                {
                    var calendar = new Calendar();
                    calendar.SetToNow();
                    calendar.AddDays(-1);
                    var yesterday = calendar.GetDateTime();

                    // Get history from yesterday onwards
                    var history = await ActivitySensor.GetSystemHistoryAsync(yesterday);

                    ScenarioOutput_Count.Text = history.Count.ToString();
                    if (history.Count > 0)
                    {
                        var reading1 = history[0];
                        ScenarioOutput_Activity1.Text = reading1.Activity.ToString();
                        ScenarioOutput_Confidence1.Text = reading1.Confidence.ToString();
                        ScenarioOutput_Timestamp1.Text = reading1.Timestamp.ToString("u");

                        var readingN = history[history.Count - 1];
                        ScenarioOutput_ActivityN.Text = readingN.Activity.ToString();
                        ScenarioOutput_ConfidenceN.Text = readingN.Confidence.ToString();
                        ScenarioOutput_TimestampN.Text = readingN.Timestamp.ToString("u");
                    }
                }
                else
                {
                    rootPage.NotifyUser("No activity sensors found", NotifyType.ErrorMessage);
                }
            }
            else
            {
                rootPage.NotifyUser("Access to activity sensors is denied", NotifyType.ErrorMessage);
            }
        }
Exemplo n.º 7
0
 private static long GetTimeFromDateValue(DateTime untilDate)
 {
     if (untilDate == null)
     {
         return -1;
     }
     Calendar dateValue = new Calendar();
     dateValue.Year = untilDate.Year;//.set(Calendar.YEAR, untilDate.year());
     dateValue.Month = untilDate.Month - 1;//TODO 为什么要减1         .set(Calendar.MONTH, untilDate.month() - 1);
     dateValue.Day = untilDate.Day;//.set(Calendar.DAY_OF_MONTH, untilDate.day());
     dateValue.Hour = untilDate.Hour;//.set(Calendar.HOUR_OF_DAY, 0);
     dateValue.Minute = untilDate.Minute;//.set(Calendar.MINUTE, 0);
     dateValue.Second = untilDate.Second;//.set(Calendar.SECOND, 0);
     dateValue.Nanosecond = untilDate.Millisecond * 1000;//.set(Calendar.MILLISECOND, 0);
     return dateValue.GetDateTime().Ticks / TimeSpan.TicksPerMillisecond;//.getTimeInMillis();
 }
Exemplo n.º 8
0
    /**
 * This isn't a regular method, because there isn't exist utc date. It
 * convert date for example 2014/1/1 09:00 +0800 -> 2014/1/1 09:00 +0000
 *
 * @return utc date
 */
    private static DateTime ConvertDateToUTCDate(DateTime date, Calendar taskCal, Calendar utcCal)
    {
        taskCal.SetDateTime(date);
        utcCal.SetDateTime(taskCal.GetDateTime().DateTime.ToUniversalTime());
        return utcCal.GetDateTime().DateTime;
        //taskCal.setTime(date);
        //int year = taskCal.get(Calendar.YEAR);
        //int month = taskCal.get(Calendar.MONTH);
        //int day = taskCal.get(Calendar.DAY_OF_MONTH);
        //int hourOfDay = taskCal.get(Calendar.HOUR_OF_DAY);
        //int minute = taskCal.get(Calendar.MINUTE);
        //int second = taskCal.get(Calendar.SECOND);
        //utcCal.clear();
        //utcCal.set(year, month, day, hourOfDay, minute, second);
        //return utcCal.getTime();
    }
Exemplo n.º 9
0
        private void ShowResults_Click(object sender, RoutedEventArgs e)
        {
            // This scenario uses the Windows.Globalization.Calendar class to enumerate through a calendar and
            // perform calendar math
            StringBuilder results = new StringBuilder();

            results.AppendLine("The number of years in each era of the Japanese era calendar is not regular. " +
                               "It is determined by the length of the given imperial era:");
            results.AppendLine();

            // Create Japanese calendar.
            Calendar calendar = new Calendar(new[] { "en-US" }, CalendarIdentifiers.Japanese, ClockIdentifiers.TwentyFourHour);

            // Enumerate all supported years in all supported Japanese eras.
            for (calendar.Era = calendar.FirstEra; true; calendar.AddYears(1))
            {
                // Process current era.
                results.AppendLine("Era " + calendar.EraAsString() + " contains " + calendar.NumberOfYearsInThisEra + " year(s)");

                // Enumerate all years in this era.
                for (calendar.Year = calendar.FirstYearInThisEra; true; calendar.AddYears(1))
                {
                    // Begin sample processing of current year.

                    // Move to first day of year. Change of month can affect day so order of assignments is important.
                    calendar.Month = calendar.FirstMonthInThisYear;
                    calendar.Day   = calendar.FirstDayInThisMonth;

                    // Set time to midnight (local).
                    calendar.Period     = calendar.FirstPeriodInThisDay;  // All days have 1 or 2 periods depending on clock type
                    calendar.Hour       = calendar.FirstHourInThisPeriod; // Hours start from 12 or 0 depending on clock type
                    calendar.Minute     = 0;
                    calendar.Second     = 0;
                    calendar.Nanosecond = 0;

                    if (calendar.Year % 1000 == 0)
                    {
                        results.AppendLine();
                    }
                    else if (calendar.Year % 10 == 0)
                    {
                        results.Append(".");
                    }

                    // End sample processing of current year.

                    // Break after processing last year.
                    if (calendar.Year == calendar.LastYearInThisEra)
                    {
                        break;
                    }
                }
                results.AppendLine();

                // Break after processing last era.
                if (calendar.Era == calendar.LastEra)
                {
                    break;
                }
            }
            results.AppendLine();

            // This section shows enumeration through the hours in a day to demonstrate that the number of time units in a given period (hours in a day, minutes in an hour, etc.)
            // should not be regarded as fixed. With Daylight Saving Time and other local calendar adjustments, a given day may have not have 24 hours, and
            // a given hour may not have 60 minutes, etc.
            results.AppendLine("The number of hours in a day is not constant. " +
                               "The US calendar transitions from daylight saving time to standard time on 4 November 2012:\n");

            // Create a DateTimeFormatter to display dates
            DateTimeFormatter displayDate = new DateTimeFormatter("longdate");

            // Create a gregorian calendar for the US with 12-hour clock format
            Calendar currentCal = new Windows.Globalization.Calendar(new string[] { "en-US" }, CalendarIdentifiers.Gregorian, ClockIdentifiers.TwentyFourHour, "America/Los_Angeles");

            // Set the calendar to a the date of the Daylight Saving Time-to-Standard Time transition for the US in 2012.
            // DST ends in the America/Los_Angeles time zone at 4 November 2012 02:00 PDT = 4 November 2012 09:00 UTC.
            DateTime dstDate = new DateTime(2012, 11, 4, 9, 0, 0, DateTimeKind.Utc);

            currentCal.SetDateTime(dstDate);

            // Set the current calendar to one day before DST change. Create a second calendar for comparision and set it to one day after DST change.
            Calendar endDate = currentCal.Clone();

            currentCal.AddDays(-1);
            endDate.AddDays(1);

            // Enumerate the day before, the day of, and the day after the 2012 DST-to-Standard time transition
            while (currentCal.Day <= endDate.Day)
            {
                // Process current day.
                DateTimeOffset date = currentCal.GetDateTime();
                results.AppendFormat("{0} contains {1} hour(s)\n", displayDate.Format(date), currentCal.NumberOfHoursInThisPeriod);

                // Enumerate all hours in this day.
                // Create a calendar to represent the following day.
                Calendar nextDay = currentCal.Clone();
                nextDay.AddDays(1);
                for (currentCal.Hour = currentCal.FirstHourInThisPeriod; true; currentCal.AddHours(1))
                {
                    // Display the hour for each hour in the day.
                    results.AppendFormat("{0} ", currentCal.HourAsPaddedString(2));

                    // Break upon reaching the next period (i.e. the first period in the following day).
                    if (currentCal.Day == nextDay.Day && currentCal.Period == nextDay.Period)
                    {
                        break;
                    }
                }
                results.AppendLine();
            }

            // Display results
            OutputTextBlock.Text = results.ToString();
        }
        /// <summary>
        /// This is the click handler for the 'Default' button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Display_Click(object sender, RoutedEventArgs e)
        {
            // This scenario uses the Windows.Globalization.Calendar class to enumerate through a calendar and
            // perform calendar math
            StringBuilder results = new StringBuilder();

            results.AppendLine("The number of years in each era of the Japanese era calendar is not regular. It is determined by the length of the given imperial era:\n");

            // Create Japanese calendar.
            Calendar calendar = new Calendar(new[] { "en-US" }, CalendarIdentifiers.Japanese, ClockIdentifiers.TwentyFourHour);

            // Enumerate all supported years in all supported Japanese eras.
            for (calendar.Era = calendar.FirstEra; true; calendar.AddYears(1))
            {
                // Process current era.
                results.AppendLine("Era " + calendar.EraAsString() + " contains " + calendar.NumberOfYearsInThisEra + " year(s)");

                // Enumerate all years in this era.
                for (calendar.Year = calendar.FirstYearInThisEra; true; calendar.AddYears(1))
                {
                    // Begin sample processing of current year.

                    // Move to first day of year. Change of month can affect day so order of assignments is important.
                    calendar.Month = calendar.FirstMonthInThisYear;
                    calendar.Day = calendar.FirstDayInThisMonth;

                    // Set time to midnight (local).
                    calendar.Period = calendar.FirstPeriodInThisDay;    // All days have 1 or 2 periods depending on clock type
                    calendar.Hour = calendar.FirstHourInThisPeriod;     // Hours start from 12 or 0 depending on clock type
                    calendar.Minute = 0;
                    calendar.Second = 0;
                    calendar.Nanosecond = 0;

                    if (calendar.Year % 1000 == 0)
                    {
                        results.AppendLine();
                    }
                    else if (calendar.Year % 10 == 0)
                    {
                        results.Append(".");
                    }

                    // End sample processing of current year.

                    // Break after processing last year.
                    if (calendar.Year == calendar.LastYearInThisEra)
                    {
                        break;
                    }
                }
                results.AppendLine();

                // Break after processing last era.
                if (calendar.Era == calendar.LastEra)
                {
                    break;
                }
            }

            // This section shows enumeration through the hours in a day to demonstrate that the number of time units in a given period (hours in a day, minutes in an hour, etc.)
            // should not be regarded as fixed. With Daylight Saving Time and other local calendar adjustments, a given day may have not have 24 hours, and
            // a given hour may not have 60 minutes, etc.
            results.AppendLine("\nThe number of hours in a day is not invariable. The US calendar transitions from DST to standard time on 4 November 2012:\n");

            // Create a DateTimeFormatter to display dates
            DateTimeFormatter displayDate = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longdate");

            // Create a gregorian calendar for the US with 12-hour clock format
            Calendar currentCal = new Windows.Globalization.Calendar(new string[] { "en-US" }, CalendarIdentifiers.Gregorian, ClockIdentifiers.TwentyFourHour, "america/los_angeles");

            // Set the calendar to a the date of the Daylight Saving Time-to-Standard Time transition for the US in 2012.
            // DST ends in the US at 02:00 on 4 November 2012
            DateTime dstDate = new DateTime(2012, 11, 4);  
            currentCal.SetDateTime(dstDate);

            // Set the current calendar to one day before DST change. Create a second calendar for comparision and set it to one day after DST change.
            Calendar endDate = currentCal.Clone();
            currentCal.AddDays(-1);
            endDate.AddDays(1);

            // Enumerate the day before, the day of, and the day after the 2012 DST-to-Standard time transition
            while (currentCal.Day <= endDate.Day)
            {
                // Process current day.
                DateTimeOffset date = currentCal.GetDateTime();
                results.AppendFormat("{0} contains {1} hour(s)\n", displayDate.Format(date), currentCal.NumberOfHoursInThisPeriod);

                // Enumerate all hours in this day.
                // Create a calendar to represent the following day.
                Calendar nextDay = currentCal.Clone();
                nextDay.AddDays(1);
                for (currentCal.Hour = currentCal.FirstHourInThisPeriod; true; currentCal.AddHours(1)) 
                {
                    // Display the hour for each hour in the day.             
                    results.AppendFormat("{0} ", currentCal.HourAsPaddedString(2));

                    // Break upon reaching the next period (i.e. the first period in the following day).
                    if (currentCal.Day == nextDay.Day && currentCal.Period == nextDay.Period) 
                    {
                        break;
                    }
                }

                results.AppendLine();
            }

            // Display results
            OutputTextBlock.Text = results.ToString();
        }
Exemplo n.º 11
0
        public static DateTime DurationAddToDate(String lexicalRepresentation, DateTime date)
        {
            if (date == null)
            {
                //throw new NullPointerException();
                throw new NullReferenceException();
            }

            Calendar calendar = new Calendar();
            // TODO 此处有问题
            calendar.SetDateTime(date);
            //calendar.Second =date.mi
            if (lexicalRepresentation == null)
            {
                throw new NullReferenceException();
            }
            String s = lexicalRepresentation;
            bool positive;
            int[] idx = new int[1];
            int length = s.Length;
            bool timeRequired = false;

            idx[0] = 0;
            if (length != idx[0] && s[(idx[0])] == '-')
            {
                idx[0]++;
                positive = false;
            }
            else
            {
                positive = true;
            }

            if (length != idx[0] && s[(idx[0]++)] != 'P')
            {
                //throw new ArgumentException(s); // ,idx[0]-1);
            }

            // phase 1: chop the string into chunks
            // (where a chunk is '<number><a symbol>'
            // --------------------------------------
            int dateLen = 0;
            String[] dateParts = new String[3];
            int[] datePartsIndex = new int[3];
            while (length != idx[0] && char.IsDigit(s[idx[0]]) && dateLen < 3)
            {
                datePartsIndex[dateLen] = idx[0];
                dateParts[dateLen++] = ParsePiece(s, idx);
            }

            if (length != idx[0])
            {
                if (s[idx[0]++] == 'T')
                {
                    timeRequired = true;
                }
                else
                {
                    //throw new IllegalArgumentException(s); // ,idx[0]-1);
                }
            }

            int timeLen = 0;
            String[] timeParts = new String[3];
            int[] timePartsIndex = new int[3];
            while (length != idx[0] && IsDigitOrPeriod(s[idx[0]]) && timeLen < 3)
            {
                timePartsIndex[timeLen] = idx[0];
                timeParts[timeLen++] = ParsePiece(s, idx);
            }

            if (timeRequired && timeLen == 0)
            {
                //throw new IllegalArgumentException(s); // ,idx[0]);
            }

            if (length != idx[0])
            {
                //throw new IllegalArgumentException(s); // ,idx[0]);
            }
            if (dateLen == 0 && timeLen == 0)
            {
                //throw new IllegalArgumentException(s); // ,idx[0]);
            }

            OrganizeParts(s, dateParts, datePartsIndex, dateLen, "YMD");
            OrganizeParts(s, timeParts, timePartsIndex, timeLen, "HMS");

            int year = ParseInteger(dateParts[0]);
            int months = ParseInteger(dateParts[1]);
            int days = ParseInteger(dateParts[2]);
            int hours = ParseInteger(timeParts[0]);
            int minutes = ParseInteger(timeParts[1]);
            int seconds = ParseInteger(timeParts[2]);

            if (positive)
            {
                calendar.Year += year;
                calendar.Month += months;
                calendar.Day += days;
                calendar.Hour += hours;
                calendar.Minute += minutes;
                calendar.Second += seconds;
                //calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) + year);
                //calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + months);
                //calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + days);
                //calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) + hours);
                //calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE) + minutes);
                //calendar.set(Calendar.SECOND, calendar.get(Calendar.SECOND) + seconds);
            }
            else
            {
                calendar.Year -= year;
                calendar.Month -= months;
                calendar.Day -= days;
                calendar.Hour -= hours;
                calendar.Minute -= minutes;
                calendar.Second -= seconds;
                //calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) - year);
                //calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - months);
                //calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) - days);
                //calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - hours);
                //calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE) - minutes);
                //calendar.set(Calendar.SECOND, calendar.get(Calendar.SECOND) - seconds);
            }

            return calendar.GetDateTime().DateTime;
        }
Exemplo n.º 12
0
 public static DateTime? SetHMToDate(String timeHM, DateTime date)
 {
     if (date == null)
     {
         return null;
     }
     DateTime? timeDate = DateTimeUtils.ParseUTCTime(timeHM);
     if (timeDate == null)
     {
         return null;
     }
     Calendar calendar = new Calendar();
     calendar.SetDateTime(date);
     //int year = calendar.Year;//.get(Calendar.YEAR);
     //int month = calendar.Month;//.get(Calendar.MONTH);
     //int day = calendar.Day;//.get(Calendar.DAY_OF_MONTH);
     //calendar.SetDateTime(timeDate.Value);//.setTime(timeDate);
     //int hourOfDay = calendar.Hour;//.get(Calendar.HOUR_OF_DAY);
     //int minute = calendar.Minute;//.get(Calendar.MINUTE);
     ////calendar.clear();
     //calendar.set(year, month, day, hourOfDay, minute);
     return calendar.GetDateTime().DateTime;//.getTime();
 }
Exemplo n.º 13
0
        public static DateTime? ClearSecondOfDay(DateTime date)
        {
            if (date == null)
            {
                return null;
            }
            Calendar c = new Calendar();
            c.SetDateTime(date);
            c.Second = 0;
            return c.GetDateTime().DateTime;

            //c.setTime(date);
            //c.set(Calendar.SECOND, 0);
            //c.set(Calendar.MILLISECOND, 0);
            //return c.getTime();
        }
        /// <summary>
        /// Invoked when 'Get History' button is clicked.
        /// Depending on the user selection, this handler uses one of the overloaded
        /// 'GetSystemHistoryAsync' APIs to retrieve the pedometer history of the user
        /// </summary>
        /// <param name="sender">unused</param>
        /// <param name="e">unused</param>
        async private void GetHistory_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            IReadOnlyList<PedometerReading> historyReadings = null;
            DateTimeFormatter timestampFormatter = new DateTimeFormatter("shortdate longtime");

            // Disable subsequent history retrieval while the async operation is in progress
            GetHistory.IsEnabled = false;

            // clear previous content being displayed
            historyRecords.Clear();

            try
            {
                if (getAllHistory)
                {
                    DateTime dt = DateTime.FromFileTimeUtc(0);
                    DateTimeOffset fromBeginning = new DateTimeOffset(dt);
                    rootPage.NotifyUser("Retrieving all available History", NotifyType.StatusMessage);
                    historyReadings = await Pedometer.GetSystemHistoryAsync(fromBeginning);
                }
                else
                {
                    String notificationString = "Retrieving history from: ";
                    Calendar calendar = new Calendar();
                    calendar.ChangeClock("24HourClock");

                    // DateTime picker will also include hour, minute and seconds from the the system time.
                    // Decrement the same to be able to correctly add TimePicker values.

                    calendar.SetDateTime(FromDate.Date);
                    calendar.AddNanoseconds(-calendar.Nanosecond);
                    calendar.AddSeconds(-calendar.Second);
                    calendar.AddMinutes(-calendar.Minute);
                    calendar.AddHours(-calendar.Hour);
                    calendar.AddSeconds(Convert.ToInt32(FromTime.Time.TotalSeconds));

                    DateTimeOffset fromTime = calendar.GetDateTime();

                    calendar.SetDateTime(ToDate.Date);
                    calendar.AddNanoseconds(-calendar.Nanosecond);
                    calendar.AddSeconds(-calendar.Second);
                    calendar.AddMinutes(-calendar.Minute);
                    calendar.AddHours(-calendar.Hour);
                    calendar.AddSeconds(Convert.ToInt32(ToTime.Time.TotalSeconds));

                    DateTimeOffset toTime = calendar.GetDateTime();

                    notificationString += timestampFormatter.Format(fromTime);
                    notificationString += " To ";
                    notificationString += timestampFormatter.Format(toTime);

                    if (toTime.ToFileTime() < fromTime.ToFileTime())
                    {
                        rootPage.NotifyUser("Invalid time span. 'To Time' must be equal or more than 'From Time'", NotifyType.ErrorMessage);

                        // Enable subsequent history retrieval while the async operation is in progress
                        GetHistory.IsEnabled = true;
                    }
                    else
                    {
                        TimeSpan span;
                        span = TimeSpan.FromTicks(toTime.Ticks - fromTime.Ticks);
                        rootPage.NotifyUser(notificationString, NotifyType.StatusMessage);
                        historyReadings = await Pedometer.GetSystemHistoryAsync(fromTime, span);
                    }
                }

                if (historyReadings != null)
                {
                    foreach(PedometerReading reading in historyReadings)
                    {
                        HistoryRecord record = new HistoryRecord(reading);
                        historyRecords.Add(record);
                    }

                    rootPage.NotifyUser("History retrieval completed", NotifyType.StatusMessage);
                }
            }
            catch (UnauthorizedAccessException)
            {
                rootPage.NotifyUser("User has denied access to activity history", NotifyType.ErrorMessage);
            }

            // Finally, re-enable history retrieval
            GetHistory.IsEnabled = true;
        }
Exemplo n.º 15
0
 private static DateTime ConvertUtcDateToDate(DateTime utcDate, Calendar taskCal, Calendar utcCal)
 {
     utcCal.SetDateTime(utcDate);
     taskCal.SetDateTime(utcCal.GetDateTime().DateTime);
     return taskCal.GetDateTime().DateTime;
     //int year = utcCal.Year;//.get(Calendar.YEAR);
     //int month = utcCal.Month;//.get(Calendar.MONTH);
     //int day = utcCal.Day;//.get(Calendar.DAY_OF_MONTH);
     //int hourOfDay = utcCal.Hour;//.get(Calendar.HOUR_OF_DAY);
     //int minute = utcCal.Minute;//.get(Calendar.MINUTE);
     //int second = utcCal.Second;//.get(Calendar.SECOND);
     ////taskCal.clear();
     //taskCal.set(year, month, day, hourOfDay, minute, second);
     //return taskCal.getTime();
 }
        /// <summary>
        /// Invoked when 'Get History' button is clicked.
        /// Depending on the user selection, this handler uses one of the overloaded
        /// 'GetSystemHistoryAsync' APIs to retrieve the pedometer history of the user
        /// </summary>
        /// <param name="sender">unused</param>
        /// <param name="e">unused</param>
        async private void GetHistory_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            GetHistory.IsEnabled = false;

            // Determine if we can access pedometers
            var deviceAccessInfo = DeviceAccessInformation.CreateFromDeviceClassId(PedometerClassId);
            if (deviceAccessInfo.CurrentStatus == DeviceAccessStatus.Allowed)
            {
                // Determine if a pedometer is present
                // This can also be done using Windows::Devices::Enumeration::DeviceInformation::FindAllAsync
                var sensor = await Pedometer.GetDefaultAsync();
                if (sensor != null)
                {
                    IReadOnlyList<PedometerReading> historyReadings = null;
                    var timestampFormatter = new DateTimeFormatter("shortdate longtime");

                    // Disable subsequent history retrieval while the async operation is in progress
                    GetHistory.IsEnabled = false;

                    // clear previous content being displayed
                    historyRecords.Clear();

                    try
                    {
                        if (getAllHistory)
                        {
                            var dt = DateTime.FromFileTimeUtc(0);
                            var fromBeginning = new DateTimeOffset(dt);
                            rootPage.NotifyUser("Retrieving all available History", NotifyType.StatusMessage);
                            historyReadings = await Pedometer.GetSystemHistoryAsync(fromBeginning);
                        }
                        else
                        {
                            String notificationString = "Retrieving history from: ";
                            var calendar = new Calendar();
                            calendar.ChangeClock("24HourClock");

                            // DateTime picker will also include hour, minute and seconds from the the system time.
                            // Decrement the same to be able to correctly add TimePicker values.

                            calendar.SetDateTime(FromDate.Date);
                            calendar.AddNanoseconds(-calendar.Nanosecond);
                            calendar.AddSeconds(-calendar.Second);
                            calendar.AddMinutes(-calendar.Minute);
                            calendar.AddHours(-calendar.Hour);
                            calendar.AddSeconds(Convert.ToInt32(FromTime.Time.TotalSeconds));

                            DateTimeOffset fromTime = calendar.GetDateTime();

                            calendar.SetDateTime(ToDate.Date);
                            calendar.AddNanoseconds(-calendar.Nanosecond);
                            calendar.AddSeconds(-calendar.Second);
                            calendar.AddMinutes(-calendar.Minute);
                            calendar.AddHours(-calendar.Hour);
                            calendar.AddSeconds(Convert.ToInt32(ToTime.Time.TotalSeconds));

                            DateTimeOffset toTime = calendar.GetDateTime();

                            notificationString += timestampFormatter.Format(fromTime);
                            notificationString += " To ";
                            notificationString += timestampFormatter.Format(toTime);

                            if (toTime.ToFileTime() < fromTime.ToFileTime())
                            {
                                rootPage.NotifyUser("Invalid time span. 'To Time' must be equal or more than 'From Time'", NotifyType.ErrorMessage);

                                // Enable subsequent history retrieval while the async operation is in progress
                                GetHistory.IsEnabled = true;
                            }
                            else
                            {
                                TimeSpan span = TimeSpan.FromTicks(toTime.Ticks - fromTime.Ticks);
                                rootPage.NotifyUser(notificationString, NotifyType.StatusMessage);
                                historyReadings = await Pedometer.GetSystemHistoryAsync(fromTime, span);
                            }
                        }

                        if (historyReadings != null)
                        {
                            foreach (PedometerReading reading in historyReadings)
                            {
                                HistoryRecord record = new HistoryRecord(reading);
                                historyRecords.Add(record);

                                // Get at most 100 records (number is arbitrary chosen for demonstration purposes)
                                if (historyRecords.Count == 100)
                                {
                                    break;
                                }
                            }

                            rootPage.NotifyUser("History retrieval completed", NotifyType.StatusMessage);
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {
                        rootPage.NotifyUser("User has denied access to activity history", NotifyType.ErrorMessage);
                    }

                    // Finally, re-enable history retrieval
                    GetHistory.IsEnabled = true;
                }
                else
                {
                    rootPage.NotifyUser("No pedometers found", NotifyType.ErrorMessage);
                }
            }
            else
            {
                rootPage.NotifyUser("Access to pedometers is denied", NotifyType.ErrorMessage);
            }
        }