当前位置: 首页>>代码示例>>C#>>正文


C# DateTime.AddHours方法代码示例

本文整理汇总了C#中System.DateTime.AddHours方法的典型用法代码示例。如果您正苦于以下问题:C# DateTime.AddHours方法的具体用法?C# DateTime.AddHours怎么用?C# DateTime.AddHours使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.DateTime的用法示例。


在下文中一共展示了DateTime.AddHours方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Main

    static void Main()
    {
        Console.Write("Enter date in the the format d.m.y h:m:s: ");
        string fullDate = Console.ReadLine();

        //withouth validation because the code will become too long
        //the validation is the same as the prev ex
        string[] parts = fullDate.Split(' ');
        string[] date = parts[0].Split('.');
        string[] time = parts[1].Split(':');

        int day = int.Parse(date[0]);
        int month = int.Parse(date[1]);
        int year = int.Parse(date[2]);

        int hours = int.Parse(time[0]);
        int minutes = int.Parse(time[1]);
        int seconds = int.Parse(time[2]);

        System.Globalization.CultureInfo cultureInfo =
        new System.Globalization.CultureInfo("bg-BG");

        //27.1.2013 21:21:43
        DateTime result = new DateTime(year, month, day, hours, minutes, seconds);
        Console.WriteLine(result.AddHours(6.5));
        Console.WriteLine(result.AddHours(6.5).DayOfWeek);
    }
开发者ID:hristo-iliev,项目名称:TelerikHW,代码行数:27,代码来源:PrintNewDateAndTime.cs

示例2: NoOverlappingIndentifierShouldPass

        public void NoOverlappingIndentifierShouldPass()
        {
            // Assert
            var start = new DateTime(1999, 1, 1);
            var finish = new DateTime(2020, 12, 31);
            var validity = new DateRange(start, finish);
            var system = new SourceSystem { Name = "Test" };
            var expectedPartyRole = new PartyRole() { PartyRoleType = "PartyRole" };
            var expected = new PartyRoleMapping { System = system, MappingValue = "1", Validity = validity, PartyRole = expectedPartyRole };
            var list = new List<PartyRoleMapping> { expected };
            var repository = new Mock<IRepository>();
            repository.Setup(x => x.Queryable<PartyRoleMapping>()).Returns(list.AsQueryable());
            repository.Setup(x => x.FindOne<PartyRole>(It.IsAny<int>())).Returns(expectedPartyRole);

            var identifier = new EnergyTrading.Mdm.Contracts.MdmId
            {
                SystemName = "Test",
                Identifier = "1",
                StartDate = start.AddHours(-10),
                EndDate = start.AddHours(-5)
            };

            var request = new CreateMappingRequest() { EntityId = 1, Mapping = identifier };
            var rule = new PartyRoleCreateMappingdNoOverlappingRule<PartyRole, PartyRoleMapping>(repository.Object);

            // Act
            var result = rule.IsValid(request);

            // Assert
            repository.Verify(x => x.FindOne<PartyRole>(It.IsAny<int>()));
            Assert.IsTrue(result, "Rule failed");
        }
开发者ID:RaoulHolzer,项目名称:EnergyTrading-MDM-Sample,代码行数:32,代码来源:PartyRoleCreateMappingdNoOverlappingRuleFixture.cs

示例3: Setup

 public void Setup()
 {
     now = DateTime.Now;
     inOneHour = now.AddHours(1);
     inTwoHours = now.AddHours(2);
     inThreeHours = now.AddHours(3);
 }
开发者ID:Quicks01ver,项目名称:Orcomp,代码行数:7,代码来源:DateIntervalTestBase.cs

示例4: GetResult

 public IHttpActionResult GetResult(DateTime date, int hour, string name, string eNodebName, byte sectorId)
 {
     CollegeInfo college = _collegeRepository.FirstOrDefault(x => x.Name == name);
     if (college == null) return BadRequest("Bad College Name!");
     ENodeb eNodeb = _eNodebRepository.FirstOrDefault(x => x.Name == eNodebName);
     if (eNodeb == null) return BadRequest("Bad ENodeb Name!");
     DateTime time = date.AddHours(hour);
     College4GTestResults result = _repository.FirstOrDefault(
         x => x.TestTime == time && x.CollegeId == college.Id);
     if (result == null)
         return Ok(new College4GTestResults
         {
             TestTime = date.AddHours(hour),
             CollegeId = college.Id,
             ENodebId = eNodeb.ENodebId,
             AccessUsers = 20,
             DownloadRate = 8000,
             UploadRate = 3000,
             SectorId = sectorId,
             Rsrp = -90,
             Sinr = 14
         });
     result.ENodebId = eNodeb.ENodebId;
     result.SectorId = sectorId;
     return Ok(result);
 }
开发者ID:ouyh18,项目名称:LteTools,代码行数:26,代码来源:College4GTestController.cs

示例5: getStatiscNullByBetweenTime

 public static List<DayPunchCardUser> getStatiscNullByBetweenTime(DateTime start, DateTime end, char type, byte status)
 {
     using (DataClassesEduDataContext dc = new DataClassesEduDataContext())
     {
         if (type == '1')
         {
             var bb = from user in dc.Users
                      where user.UserType == '1' &&
                      !(from kq in dc.KQ_PunchCardRecords where kq.PunchCardType == type && kq.Time > start && kq.Time < end select kq.PunchCardUserId).Contains(user.Key)
                      && !(from at in dc.KQ_Attendance where at.starttime <= start.AddHours(8) && at.endtime >= start.AddHours(8) select at.userid).Contains(user.Key)
                      select new DayPunchCardUser { 工号 = user.JobNumber, 姓名 = user.TrueName, 电话长号 = user.changhao, 电话短号 = user.duanhao, 序号 = (user.orderNo == null) ? 0 : (int)user.orderNo };
             return bb.OrderBy(a => a.序号).ToList<DayPunchCardUser>();
         }
         if (type == '2')
         {
             var bb = from user in dc.Users
                      where user.UserType == '1' &&
                      !(from kq in dc.KQ_PunchCardRecords where kq.PunchCardType == type && kq.Time > start && kq.Time < end select kq.PunchCardUserId).Contains(user.Key)
                      && !(from at in dc.KQ_Attendance where at.starttime <= start.AddHours(16) && at.endtime >= start.AddHours(16) select at.userid).Contains(user.Key)
                      select new DayPunchCardUser { 工号 = user.JobNumber, 姓名 = user.TrueName, 电话长号 = user.changhao, 电话短号 = user.duanhao, 序号 = (user.orderNo == null) ? 0 : (int)user.orderNo };
             return bb.OrderBy(a => a.序号).ToList<DayPunchCardUser>();
         }
         return null;
     }
 }
开发者ID:kexinn,项目名称:Edu,代码行数:25,代码来源:DayStatisticKQ.cs

示例6: OverlappingIdentifierFails

        public void OverlappingIdentifierFails()
        {
            // Assert
            var start = new DateTime(1999, 1, 1);
            var finish = new DateTime(2020, 12, 31);
            var validity = new DateRange(start, finish);
            var system = new SourceSystem { Name = "Test" };
            var expected = new SourceSystemMapping { System = system, MappingValue = "1", Validity = validity };
            var list = new System.Collections.Generic.List<SourceSystemMapping> { expected };
            var repository = new Mock<IRepository>();
            repository.Setup(x => x.Queryable<SourceSystemMapping>()).Returns(list.AsQueryable());

            var identifier = new EnergyTrading.Mdm.Contracts.MdmId
            {
                SystemName = "Test",
                Identifier = "1",
                StartDate = start.AddHours(5),
                EndDate = start.AddHours(10)
            };

            var request = new AmendMappingRequest() { EntityId = 1, Mapping = identifier, MappingId = 1 };

            var rule = new AmendMappingNoOverlappingRule<SourceSystemMapping>(repository.Object);

            // Act
            var result = rule.IsValid(request);

            // Assert
            repository.Verify(x => x.Queryable<SourceSystemMapping>());
            Assert.IsFalse(result, "Rule failed");
        }
开发者ID:RWE-Nexus,项目名称:EnergyTrading-MDM,代码行数:31,代码来源:AmendMappingNoOverlappingRuleFixture.cs

示例7: ResetTimer

        /// <summary>
        /// Resets the activation timer to fire when the next future revision of any document needs to become current.
        /// </summary>
        /// <remarks>
        /// This is called any time a new revision is stored, preventing us from having to poll periodically.
        /// </remarks>
        internal void ResetTimer(DateTime runDate, DateTime now)
        {
            // Don't wait at all if we were asked to wait forever.
            if (runDate == DateTime.MaxValue)
                return;

            // Never wait more than an hour from now.  Running early is ok.
            if (runDate > now.AddHours(1))
                runDate = now.AddHours(1);

            // If rundate as passed, use now.
            if (runDate < now)
                runDate = now;

            // If the rundate is later than we're already waiting, then ignore it.
            if (runDate >= _nextRunDate)
                return;

            // Hold on to the date for comparison next time around
            _nextRunDate = runDate;

            // Determine the wait time
            var wait = (long) (runDate - now).TotalMilliseconds;
            if (wait < 0) wait = 0;

            // Set the timer.
            _timer.Change(wait, -1);
        }
开发者ID:jggutierrez,项目名称:RavenDB-TemporalVersioning,代码行数:34,代码来源:TemporalActivator.cs

示例8: CheckPostponeIsPossible

        public bool CheckPostponeIsPossible(int performanceId, DateTime date, int venueId)
        {
            IPerformanceDao dao = DALFactory.CreatePerformanceDao(database);
            IVenueDao venueDao = DALFactory.CreateVenueDao(database);
            Performance toPostpone = dao.findById(performanceId);
            IList<Performance> otherPerformances = dao.FindPerormanceByDay(date);

            bool foundConflict = false;
            foreach(Performance p in otherPerformances)
            {
                if(p.Id == toPostpone.Id)
                {
                    continue;
                }

                DateTime postPoneDate = new DateTime(date.Year, date.Month, date.Day, date.Hour, 0, 0);
                DateTime currentDate = new DateTime(p.StagingTime.Year, p.StagingTime.Month, p.StagingTime.Day, p.StagingTime.Hour, 0, 0);

                if (toPostpone.Artist.Id == p.Artist.Id)
                {
                   if(postPoneDate >= currentDate.AddHours(-2) && postPoneDate <= currentDate.AddHours(2))
                    {
                        foundConflict = true;
                        break;
                    }
                }
                if(p.Venue.Id == venueId && postPoneDate == currentDate)
                {
                    foundConflict = true;
                    break;
                }

            }
            return !foundConflict;
        }
开发者ID:wlumetsberger,项目名称:SWK5-WEA5-Projekt,代码行数:35,代码来源:QueryService.cs

示例9: Next

        public override DateTime Next(DateTime time, out bool changed)
        {
            changed = false;

            if (Values.Count < 1)
            {
                return time;
            }
            if (Type == CGtd.DATES_TYPE_EACH)
            {
                return time.AddHours(Values[0]);
            }
            if (Type == CGtd.DATES_TYPE_WHEN)
            {
                int idx = time.Hour;
                int tmp = NextValue(idx, changed);
                if (tmp > 0)
                {
                    return time.AddHours(tmp);
                }
                if (tmp < 0)
                {
                    changed = true;
                    return time.AddDays(1).AddHours(Values[0] - idx);
                }
            }
            return time;
        }
开发者ID:burstas,项目名称:rmps,代码行数:28,代码来源:Hour.cs

示例10: EventRecurTestForm_Load

        //=====================================================================

        /// <summary>
        /// This loads the time zone information from the registry when the form is loaded and sets the form
        /// defaults.
        /// </summary>
        /// <param name="sender">The sender of the event</param>
        /// <param name="e">The event arguments</param>
        private void EventRecurTestForm_Load(object sender, EventArgs e)
        {
            TimeZoneRegInfo.LoadTimeZoneInfo();

            // Load the time zone combo box.  The first entry will be for no time zone.
            cboTimeZone.Items.Add("No time zone");

            foreach(VTimeZone vtz in VCalendar.TimeZones)
                cboTimeZone.Items.Add(vtz.TimeZoneId.Value);

            cboTimeZone.SelectedIndex = 0;

            DateTime dtDate = new DateTime(DateTime.Today.Year, 1, 1);
            dtpStartDate.Value = dtDate;
            dtpEndDate.Value = dtDate.AddMonths(3);

            txtCalendar.Text = String.Format(
                "BEGIN:VEVENT\r\n" +
                "DTSTART:{0}\r\n" +
                "DTEND:{1}\r\n" +
                "RRULE:FREQ=DAILY;COUNT=10;INTERVAL=5\r\n" +
                "END:VEVENT\r\n",
                dtDate.AddHours(9).ToUniversalTime().ToString(ISO8601Format.BasicDateTimeUniversal),
                dtDate.AddHours(10).ToUniversalTime().ToString(ISO8601Format.BasicDateTimeUniversal));
        }
开发者ID:modulexcite,项目名称:PDI,代码行数:33,代码来源:EventRecurTestForm.cs

示例11: GivenAnOwnerAndRepoAndEmailWhenGettingTheLastCommit

        public void GivenAnOwnerAndRepoAndEmailWhenGettingTheLastCommit()
        {
            _owner = "my owner";
            _repo = "my repo";
            _userEmail = "email1";
            _expectedResource = string.Format("/repos/{0}/{1}", _owner, _repo);
            _commitDate = DateTime.UtcNow;

            _returnedCommits = new List<RepoCommit>
            {
                new RepoCommit
                {
                    Commit = new Commit
                    {
                        CommitCommitter = new CommitCommitter
                        {
                            Email = _userEmail,
                            Date = _commitDate.AddHours(-1)
                        }
                    }
                },
                new RepoCommit
                {
                    Commit = new Commit
                    {
                        CommitCommitter = new CommitCommitter
                        {
                            Email = "email2",
                            Date = _commitDate.AddHours(1)
                        }
                    }
                },
                new RepoCommit
                {
                    Commit = new Commit
                    {
                        CommitCommitter = new CommitCommitter
                        {
                            Email = _userEmail,
                            Date = _commitDate
                        }
                    }
                }
            };

            var mockRestResponse = new Mock<IRestResponse<List<RepoCommit>>>();
            mockRestResponse
                .SetupGet(response => response.Data)
                .Returns(_returnedCommits);

            _mockRestClient = new Mock<IRestClient>();
            _mockRestClient
                .Setup(client => client.Execute<List<RepoCommit>>(It.IsAny<IRestRequest>()))
                .Returns(mockRestResponse.Object);
            ;

            var service = new RepoCommittersService(_mockRestClient.Object);
            _repoCommit = service.GetCommitterLastCommit(_owner, _repo, _userEmail);
        }
开发者ID:jonathanrelf,项目名称:HackTrack,代码行数:59,代码来源:RepoCommittersServiceTests.cs

示例12: NoFilterTest

        public void NoFilterTest()
        {
            DateTime date1 = new DateTime( 2011, 4, 12 );

            CalendarDateDiff calendarDateDiff = new CalendarDateDiff();
            Assert.AreEqual( calendarDateDiff.Difference( date1, date1.AddHours( 1 ) ), new TimeSpan( 1, 0, 0 ) );
            Assert.AreEqual( calendarDateDiff.Difference( date1, date1.AddHours( -1 ) ), new TimeSpan( -1, 0, 0 ) );
        }
开发者ID:jwg4,项目名称:date-difference,代码行数:8,代码来源:CalendarDateDiffTest.cs

示例13: Test_ExitVehicle_AlreadyExited_ShouldReturnErrorMessage

 public void Test_ExitVehicle_AlreadyExited_ShouldReturnErrorMessage()
 {
     var park = new VehiclePark(1, 2);
     var car = new Car("CA1011AH", "John Smith", 1);
     DateTime insertDate = new DateTime(2015, 5, 10, 10, 0, 0);
     park.InsertCar(car, 1, 1, insertDate);
     park.ExitVehicle("CA1011AH", insertDate.AddHours(2), 10.0M);
     string message = park.ExitVehicle("CA1011AH", insertDate.AddHours(2), 10.0M);
     Assert.AreEqual("There is no vehicle with license plate CA1011AH in the park", message);
 }
开发者ID:exploitx3,项目名称:HighQualityCode,代码行数:10,代码来源:ExitVehicleTests.cs

示例14: Average

        /// <summary>
        /// Function that averages a series based on a defined Time-Interval
        /// </summary>
        /// <param name="s">Input Series</param>
        /// <param name="tInterval">Averaging Time-Interval</param>
        /// <returns></returns>
        public static Series Average(Series s, TimeInterval tInterval)
        {
            Series rval = s.Clone();
            if (s.Count == 0)
                return rval;

            // Define starting date of averaging process
            DateTime t = new DateTime(s[0].DateTime.Year, s[0].DateTime.Month, s[0].DateTime.Day,
                s[0].DateTime.Hour, 0, 0);

            // Find which averaging process to accomplish
            if (tInterval == TimeInterval.Daily)
            {
                // Define series time-interval
                rval.TimeInterval = TimeInterval.Daily;
                // Loop through the dates
                while (t < s[s.Count - 1].DateTime.Date)
                {
                    // Get the series subset based on the averaging time-interval
                    Series sTemp = s.Subset(t, t.AddDays(1));
                    // Average the values of the subset
                    DoAverage(rval, t, sTemp);
                    // Increment DateTime by averaging time-interval
                    t = t.AddDays(1);
                }
            }
            // Ditto on the other processes below
            else if (tInterval == TimeInterval.Monthly)
            {
                rval.TimeInterval = TimeInterval.Monthly;
                while (t < s[s.Count - 1].DateTime.Date)
                {
                    Series sTemp = s.Subset(t, t.AddMonths(1));
                    DoAverage(rval, t, sTemp);
                    t = t.AddMonths(1);
                }
            }
            else if (tInterval == TimeInterval.Hourly)
            {
                rval.TimeInterval = TimeInterval.Hourly;
                while (t < s.MaxDateTime)
                {

                    Series sTemp = Math.Subset(s, new DateRange(t, t.AddHours(1)), false);
                    DoAverage(rval, t, sTemp);
                    t = t.AddHours(1);

                }
            }
            else
            { throw new Exception("Time Interval " + tInterval.ToString() + " not supported!"); }

            return rval;
        }
开发者ID:usbr,项目名称:Pisces,代码行数:60,代码来源:Math.cs

示例15: Run

        static void Run()
        { 
            // ExStart: PagingSupportForListingAppointments
            using (IEWSClient client = EWSClient.GetEWSClient("exchange.domain.com", "username", "password"))
            {
                try
                {
                    Appointment[] appts = client.ListAppointments();
                    Console.WriteLine(appts.Length);
                    DateTime date = DateTime.Now;
                    DateTime startTime = new DateTime(date.Year, date.Month, date.Day, date.Hour, 0, 0);
                    DateTime endTime = startTime.AddHours(1);
                    int appNumber = 10;
                    Dictionary<string, Appointment> appointmentsDict = new Dictionary<string, Appointment>();
                    for (int i = 0; i < appNumber; i++)
                    {
                        startTime = startTime.AddHours(1);
                        endTime = endTime.AddHours(1);
                        string timeZone = "America/New_York";
                        Appointment appointment = new Appointment(
                            "Room 112",
                            startTime,
                            endTime,
                            "[email protected]",
                            "[email protected]");
                        appointment.SetTimeZone(timeZone);
                        appointment.Summary = "NETWORKNET-35157_3 - " + Guid.NewGuid().ToString();
                        appointment.Description = "EMAILNET-35157 Move paging parameters to separate class";
                        string uid = client.CreateAppointment(appointment);
                        appointmentsDict.Add(uid, appointment);
                    }
                    AppointmentCollection totalAppointmentCol = client.ListAppointments();

                    ///// LISTING APPOINTMENTS WITH PAGING SUPPORT ///////
                    int itemsPerPage = 2;
                    List<AppointmentPageInfo> pages = new List<AppointmentPageInfo>();
                    AppointmentPageInfo pagedAppointmentCol = client.ListAppointmentsByPage(itemsPerPage);
                    Console.WriteLine(pagedAppointmentCol.Items.Count);
                    pages.Add(pagedAppointmentCol);
                    while (!pagedAppointmentCol.LastPage)
                    {
                        pagedAppointmentCol = client.ListAppointmentsByPage(itemsPerPage, pagedAppointmentCol.PageOffset + 1);
                        pages.Add(pagedAppointmentCol);
                    }
                    int retrievedItems = 0;
                    foreach (AppointmentPageInfo folderCol in pages)
                        retrievedItems += folderCol.Items.Count;
                }
                finally
                {
                }
            }
            // ExEnd: PagingSupportForListingAppointments
        }
开发者ID:aspose-email,项目名称:Aspose.Email-for-.NET,代码行数:54,代码来源:PagingSupportForListingAppointments.cs


注:本文中的System.DateTime.AddHours方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。