CSharp examples for System:DateTime Month
Attempts to create date from string representation such as +7days or -2months
using System;// w ww . j av a 2 s . c o m public class Main{ /// <summary> /// Attempts to create date from string representation such as +7days or -2months /// </summary> public static DateTime? GetCalculatedDateTime(object dateRepresentation) { try { string val = dateRepresentation.ToString().ToLower(); if (val == "now") return DateTime.Now; int integerVal = 0; bool isMinus = val.StartsWith("-"); bool isPlus = val.StartsWith("+"); val = val.Replace("-", "").Replace("+", ""); if ((isMinus) || (isPlus)) { if (val.Contains("days")) { integerVal = val.Replace("days", "").ConvertToInt32(0); if (integerVal != 0) return (isMinus) ? DateTime.Now.AddDays(-integerVal) : DateTime.Now.AddDays(integerVal); } else if (val.Contains("months")) { integerVal = val.Replace("months", "").ConvertToInt32(0); if (integerVal != 0) return (isMinus) ? DateTime.Now.AddMonths(-integerVal) : DateTime.Now.AddDays(integerVal); } else if (val.Contains("years")) { integerVal = val.Replace("years", "").ConvertToInt32(0); if (integerVal != 0) return (isMinus) ? DateTime.Now.AddYears(-integerVal) : DateTime.Now.AddDays(integerVal); } } return null; } catch (Exception) { return null; } } }