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


C# DateTime.GetValueOrDefault方法代码示例

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


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

示例1: testNullableDateTimeGetValueOrDefault

        public void testNullableDateTimeGetValueOrDefault()
        {
            DateTime? e = null;

            DateTime def = e.GetValueOrDefault();
            Assert.AssertEquals(default(DateTime), def);
            
            e = new DateTime(2002, 2, 2);
            def = e.GetValueOrDefault();
            Assert.AssertEquals(new DateTime(2002, 2, 2), def);

            e = null;
            def = e.GetValueOrDefault();
            Assert.AssertEquals( default(DateTime), def);
        }
开发者ID:Xtremrules,项目名称:dot42,代码行数:15,代码来源:TestNullableDateTime.cs

示例2: IsBirthday

 internal static bool IsBirthday(DateTime? birthday)
 {
     DateTime bday = birthday.GetValueOrDefault();
     if (bday > DateTime.Today)
         return false;
     return true;
 }
开发者ID:Nness,项目名称:Silver-QrCode-Generator,代码行数:7,代码来源:StringValidation.cs

示例3: Update

        public void Update(Account selectedAccount, DateTime? start, DateTime? end)
        {
            Start = start;
            End = end;
            var transactions = Dao.Query(GetCurrentRange(start, end, x => x.AccountId == selectedAccount.Id)).OrderBy(x => x.Date);
            Transactions = transactions.Select(x => new AccountDetailData(x, selectedAccount)).ToList();
            if (start.HasValue)
            {
                var pastDebit = Dao.Sum(x => x.Debit, GetPastRange(start, x => x.AccountId == selectedAccount.Id));
                var pastCredit = Dao.Sum(x => x.Credit, GetPastRange(start, x => x.AccountId == selectedAccount.Id));
                var pastExchange = Dao.Sum(x => x.Exchange, GetPastRange(start, x => x.AccountId == selectedAccount.Id));
                if (pastCredit > 0 || pastDebit > 0)
                {
                    Summaries.Add(new AccountSummaryData(Resources.TransactionTotal, Transactions.Sum(x => x.Debit), Transactions.Sum(x => x.Credit)));
                    var detailValue =
                        new AccountDetailData(
                        new AccountTransactionValue
                        {
                            Date = start.GetValueOrDefault(),
                            Name = Resources.BalanceBroughtForward,
                            Credit = pastCredit,
                            Debit = pastDebit,
                            Exchange = pastExchange
                        }, selectedAccount) { IsBold = true };
                    Transactions.Insert(0, detailValue);
                }
            }
            if (end.HasValue && end != start)
            {
                var futureDebit = Dao.Sum(x => x.Debit, GetFutureRange(end, x => x.AccountId == selectedAccount.Id));
                var futureCredit = Dao.Sum(x => x.Credit, GetFutureRange(end, x => x.AccountId == selectedAccount.Id));
                var futureExchange = Dao.Sum(x => x.Exchange, GetFutureRange(end, x => x.AccountId == selectedAccount.Id));
                if (futureCredit > 0 || futureDebit > 0)
                {
                    Summaries.Add(new AccountSummaryData(Resources.DateRangeTotal, Transactions.Sum(x => x.Debit), Transactions.Sum(x => x.Credit)));
                    var detailValue =
                        new AccountDetailData(
                        new AccountTransactionValue
                        {
                            Date = end.GetValueOrDefault(),
                            Name = Resources.BalanceAfterDate,
                            Credit = futureCredit,
                            Debit = futureDebit,
                            Exchange = futureExchange
                        }, selectedAccount) { IsBold = true };
                    Transactions.Add(detailValue);
                }
            }

            Summaries.Add(new AccountSummaryData(Resources.GrandTotal, Transactions.Sum(x => x.Debit), Transactions.Sum(x => x.Credit)));

            for (var i = 0; i < Transactions.Count; i++)
            {
                Transactions[i].Balance = (Transactions[i].Debit - Transactions[i].Credit);
                if (i > 0) (Transactions[i].Balance) += (Transactions[i - 1].Balance);
            }
        }
开发者ID:jgera,项目名称:SambaPOS-3,代码行数:57,代码来源:AccountTransactionSummary.cs

示例4: AgeAt

 public static int AgeAt(this DateTime dt, DateTime? atDate = null)
 {
     var ageAtDate = atDate.GetValueOrDefault(DateTime.UtcNow).Date;
     var age = ageAtDate.Year - dt.Year;
     if (dt > ageAtDate.AddYears(-age)) age--;
     return age;
 }
开发者ID:Philo,项目名称:FluentValidationSample,代码行数:7,代码来源:DateTimeExtensions.cs

示例5: WithShoe

        public static ShoeTrackerDbContext WithShoe(this ShoeTrackerDbContext context, 
            string name, 
            string userId,
            DateTime? firstUsedDate=null, 
            DateTime? lastUsedDate=null, 
            decimal? maximumDistance=null,
            string brand=null)
        {
            var maxShoeId = 1L;
            if (context.Shoes.Any())
            {
                maxShoeId = context.Shoes.Max(s => s.ShoeId);
            }
            var shoe = new Shoe
            {
                CreatedAt = DateTime.Now,
                FirstUsed = firstUsedDate.GetValueOrDefault(DateTime.Today),
                LastUsed = lastUsedDate,
                MaximumDistance = maximumDistance.GetValueOrDefault(400),
                Name = name,
                Brand = brand ?? "default brand",
                Workouts = new List<Workout>(),
                ShoeId = maxShoeId+1,
                UserId = userId
            };

            context.Shoes.Attach(shoe);

            return context;
        }
开发者ID:jrolstad,项目名称:shoe-tracker,代码行数:30,代码来源:DbContextExtensions.cs

示例6: WithWorkout

        public static MapMyFitnessApi WithWorkout(this MapMyFitnessApi api,
            int externalUserId,
            string accessToken,
            string name,
            decimal? distanceInMiles = null,
            string workoutId = null,
            DateTime? workoutDate = null,
            string activityType = "16",
            DateTime? lastWorkoutImported = null)
        {
            var workouts = api.GetWorkoutsByUser(externalUserId, accessToken,lastWorkoutImported);

            var distance = System.Convert.ToDouble(distanceInMiles.GetValueOrDefault(2)*(1/0.000621371m));
            workouts.Add(new Workout
            {
                name = name,
                start_datetime = workoutDate.GetValueOrDefault(DateTime.Now).ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'"),
                _links = new Links
                {
                    self = new List<Next>
                    {
                        new Next { id = workoutId ?? Guid.NewGuid().ToString()}
                    },
                    activity_type = new List<Next>
                    {
                        new Next { id = activityType}
                    },
                },
                aggregates = new WorkoutAggregate { distance_total = distance}
            });

            api.GetWorkoutsByUser(externalUserId, accessToken, lastWorkoutImported).Returns(workouts);

            return api;
        }
开发者ID:jrolstad,项目名称:shoe-tracker,代码行数:35,代码来源:MapMyFitnessApiTestExtensions.cs

示例7: CompletedChore

 public CompletedChore(Chore c, DateTime? completionDate = null, string completedBy = "")
 {
     ChoreName = c.ChoreName;
     CompletionDate = completionDate.GetValueOrDefault (DateTime.Now);
     CompletedBy = completedBy;
     ParentChoreId = c.ID;
 }
开发者ID:HofmaDresu,项目名称:ChoreImpetus,代码行数:7,代码来源:CompletedChore.cs

示例8: Stop

 public void Stop(DateTime? stopTime, string comment, IDateTimeService dateTimeService)
 {
     if (lastStartTime == null)
     {
         throw new InvalidOperationException("Task already stopped");
     }
     ApplyChange(new TaskStopped(id, stopTime.GetValueOrDefault(dateTimeService.GetUtcNow()), comment));
 }
开发者ID:jsmale,项目名称:TimeTrackerCQRS,代码行数:8,代码来源:Task.cs

示例9: TryToAssignValue

 /// <summary>
 /// A method to try to assign the value of the nullable DateTime instance. If the value is null, check off DateTimePicker control. Assign the value to DateTimePicker.Value property otherwise.
 /// </summary>
 /// <param name="dateTimePicker">DateTimePicker control to execute method for.</param>
 /// <param name="dateTime">Nullable DateTime instance to check for the value.</param>
 public static void TryToAssignValue(this DateTimePicker dateTimePicker, DateTime? dateTime)
 {
     if(dateTime.GetValueOrDefault() < dateTimePicker.MinDate || dateTime.GetValueOrDefault() > dateTimePicker.MaxDate)
     {
         dateTime = null;
     }
     if(dateTime == null)
     {
         dateTimePicker.Value = DateTime.Now;
         dateTimePicker.Checked = false;
     }
     else
     {
         dateTimePicker.Checked = true;
         dateTimePicker.Value = (DateTime)dateTime;
     }
 }
开发者ID:dr-dead,项目名称:diplomaWork,代码行数:22,代码来源:ControlExtensions.cs

示例10: EncodeDateTime

        /// <summary>
        /// 
        /// </summary>
        /// <param name="htmlHeler"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string EncodeDateTime(this HtmlHelper htmlHeler, DateTime? value)
        {
            if (value == null)
            {
                return string.Empty;
            }

            return htmlHeler.EncodeDateTime(value.GetValueOrDefault());
        }
开发者ID:shenlos,项目名称:dukous-boss,代码行数:15,代码来源:EncodeExtensions.cs

示例11: IsATimeBiggerThanBTime

        internal static bool IsATimeBiggerThanBTime(DateTime? ATime, DateTime? BTime)
        {
            DateTime atime = ATime.GetValueOrDefault();
            DateTime btime = BTime.GetValueOrDefault();

            if (atime > btime)
                return true;
            else
                return false;
        }
开发者ID:Nness,项目名称:Silver-QrCode-Generator,代码行数:10,代码来源:StringValidation.cs

示例12: Generate

 public static Employee Generate(string id = null, string name = null, int? age = null, string companyName = null, string companyId = null, DateTime? createdUtc = null, DateTime? updatedUtc = null) {
     return new Employee {
         Id = id,
         Name = name ?? RandomData.GetAlphaString(),
         Age = age ?? RandomData.GetInt(18, 100),
         CompanyName = companyName ?? RandomData.GetAlphaString(),
         CompanyId = companyId ?? ObjectId.GenerateNewId().ToString(),
         CreatedUtc = createdUtc.GetValueOrDefault(),
         UpdatedUtc = updatedUtc.GetValueOrDefault()
     };
 }
开发者ID:jmkelly,项目名称:Foundatio,代码行数:11,代码来源:Employee.cs

示例13: CalculateAge

        public static int CalculateAge(DateTime? birthdate)
        {
            DateTime bday = birthdate.GetValueOrDefault(DateTime.Now);

            var age = DateTime.Now.Year - bday.Year;

            //om man inte fyllt år i år så tar den bort 1år från age för att få rätt ålder
            if ((DateTime.Now.Month <= bday.Month) ||
                (DateTime.Now.Day >= bday.Day && DateTime.Now.Month <= bday.Month)) age--;

            return age;
        }
开发者ID:MorganAxelsson,项目名称:SuperAtleten,代码行数:12,代码来源:CountClass.cs

示例14: Dates

        /// <summary>
        /// Returns random date gen
        /// </summary>
        /// <param name="min">if not supplied, DateTime.MinValue is used</param>
        /// <param name="max">if not supplied, DateTime.MaxValue is used</param>
        public Func<DateTime> Dates(DateTime? min = null, DateTime? max = null)
        {
            var minDate = min.GetValueOrDefault(DateTime.MinValue);
            var maxDate = max.GetValueOrDefault(DateTime.MaxValue);

            if (minDate >= maxDate)
                throw new ArgumentOutOfRangeException("min >= max");

            var ticksSpan = maxDate.Ticks - minDate.Ticks;
            var factory = _random.Numbers.Doubles().BetweenZeroAndOne();

            return () => new DateTime(Convert.ToInt64(minDate.Ticks + ((double)ticksSpan * factory())));
        }
开发者ID:aliostad,项目名称:RandomGen,代码行数:18,代码来源:TimeLink.cs

示例15: GetDettaglioPartitario

        public List<MovimentoContabileBilancioDTO> GetDettaglioPartitario(EsercizioDTO esercizioDTO, IList<ContoDTO> conti, List<string> sottoconti, DateTime? dataIniziale, DateTime? dataFinale)
        {
            var idConti = conti.Select(conto => conto.ID).ToList();
            if (esercizioDTO != null)
            {
                dataIniziale = esercizioDTO.DataApertura;
                dataFinale = esercizioDTO.DataChiusura;
            }

            var result = GetServiceClient().GetDettaglioPartitario(idConti, sottoconti, dataIniziale.GetValueOrDefault(), dataFinale.GetValueOrDefault(), GetUserInfo());
            CloseService();
            return result;
        }
开发者ID:gipasoft,项目名称:Sfera,代码行数:13,代码来源:StatoPatrimonialeWCFService.cs


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