DateFormat
public DateTime DateConverter(String Date,DateFormat dateFormat) { DateTime dt = DateTime.Now; try { String[] splt = Date.Split('/'); switch (dateFormat) { case DateFormat.DDMMYYYY: dt = new DateTime(Convert.ToInt32(splt[2]), Convert.ToInt32(splt[1]), Convert.ToInt32(splt[0])); break; case DateFormat.MMDDYYYY: dt = new DateTime(Convert.ToInt32(splt[2]), Convert.ToInt32(splt[0]), Convert.ToInt32(splt[1])); break; } return dt; } catch(Exception ex) { return dt; } }
public ItemAdapter(Context context) { inflater = LayoutInflater.from(context); items = new List<SmcItem>(); // dateFormat = new SimpleDateFormat("dd-MM-yyyy"); // lint dateFormat = DateFormat.DateInstance; }
/// <summary> /// Convert from java based date to DateTime. /// </summary> private static DateTime FromParsedDate(Date value, string originalString, DateTimeStyles style, DateFormat formatter, bool forceRoundtripKind, bool useUtc) { bool assumeLocal = (style & DateTimeStyles.AssumeLocal) != 0; bool assumeUtc = useUtc || (style & DateTimeStyles.AssumeUniversal) != 0; bool roundtripKind = forceRoundtripKind || (style & DateTimeStyles.RoundtripKind) != 0; var millis = value.Time; var ticks = (millis + DateTime.EraDifferenceInMs) * TimeSpan.TicksPerMillisecond; //long offset = 0L; DateTimeKind kind; if (roundtripKind) { var tz = formatter.TimeZone; if(tz.RawOffset == 0 || originalString.EndsWith("Z")) kind = DateTimeKind.Utc; else if(tz.RawOffset == TimeZone.Default.RawOffset) kind = DateTimeKind.Local; else kind = DateTimeKind.Unspecified; } else if (assumeUtc) { kind = DateTimeKind.Utc; } else if (assumeLocal) { kind = DateTimeKind.Local; } else { kind = DateTimeKind.Unspecified; } DateTime result; if (millis == DateTime.MinValueJavaMillies) result = new DateTime(0L, kind); else { result = new DateTime(ticks, kind); } if ((style & DateTimeStyles.AdjustToUniversal) != 0) result = result.ToUniversalTime(); else if (assumeUtc) // no typo, but bad naming/semantics in the BCL result = result.ToLocalTime(); return result; }
public virtual void SetDate(DateTime? dateTime, DateFormat dateFormat) { if (dateTime == null) { ClearDate(); return; } keyboard.Send(dateFormat.DisplayValue(dateTime.Value, 0).ToString(), actionListener); keyboard.PressSpecialKey(KeyboardInput.SpecialKeys.RIGHT, actionListener); keyboard.Send(dateFormat.DisplayValue(dateTime.Value, 1).ToString(), actionListener); keyboard.PressSpecialKey(KeyboardInput.SpecialKeys.RIGHT, actionListener); keyboard.Send(dateFormat.DisplayValue(dateTime.Value, 2).ToString(), actionListener); keyboard.PressSpecialKey(KeyboardInput.SpecialKeys.RIGHT, actionListener); }
internal DateTimeFormatInfo(DateFormat dateFormat) { this.dateFormat = dateFormat; amDesignator = "AM"; pmDesignator = "PM"; dateSeparator = "/"; timeSeparator = ":"; shortDatePattern = "MM/dd/yyyy"; longDatePattern = "dddd, dd MMMM yyyy"; shortTimePattern = "HH:mm"; longTimePattern = "HH:mm:ss"; monthDayPattern = "MMMM dd"; yearMonthPattern = "yyyy MMMM"; }
public virtual void SetDate(DateTime? dateTime, DateFormat dateFormat) { if (dateTime == null) { Logger.Warn("DateTime cannot be null, value will not be set"); return; } keyboard.Send(dateFormat.DisplayValue(dateTime.Value, 0).ToString(), actionListener); keyboard.PressSpecialKey(KeyboardInput.SpecialKeys.RIGHT, actionListener); keyboard.Send(dateFormat.DisplayValue(dateTime.Value, 1).ToString(), actionListener); keyboard.PressSpecialKey(KeyboardInput.SpecialKeys.RIGHT, actionListener); keyboard.Send(dateFormat.DisplayValue(dateTime.Value, 2).ToString(), actionListener); keyboard.PressSpecialKey(KeyboardInput.SpecialKeys.RIGHT, actionListener); }
public DateRecognizerSinkFilter(DateFormat dateFormat) { this.dateFormat = dateFormat; }
public virtual void Map(object x, XElement root) { var objType = x.GetType(); var props = objType.GetProperties(); foreach (var prop in props) { var type = prop.PropertyType; if (!type.IsPublic || !prop.CanWrite) { continue; } var name = prop.Name.AsNamespaced(Namespace); var value = GetValueFromXml(root, name, prop); if (value == null) { // special case for inline list items if (type.IsGenericType) { var genericType = type.GetGenericArguments()[0]; var first = GetElementByName(root, genericType.Name); var list = (IList)Activator.CreateInstance(type); if (first != null) { var elements = root.Elements(first.Name); PopulateListFromElements(genericType, elements, list); } prop.SetValue(x, list, null); } continue; } // check for nullable and extract underlying type if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>)) { // if the value is empty, set the property to null... if (value == null || String.IsNullOrEmpty(value.ToString())) { prop.SetValue(x, null, null); continue; } type = type.GetGenericArguments()[0]; } if (type == typeof(bool)) { var toConvert = value.ToString().ToLowerInvariant(); prop.SetValue(x, XmlConvert.ToBoolean(toConvert), null); } else if (type.IsPrimitive) { if (!String.IsNullOrEmpty(value.ToString())) { prop.SetValue(x, System.Convert.ChangeType(value, type, Culture), null); } } else if (type.IsEnum) { var converted = type.FindEnumValue(value.ToString(), Culture); prop.SetValue(x, converted, null); } else if (type == typeof(Uri)) { var uri = new Uri(value.ToString(), UriKind.RelativeOrAbsolute); prop.SetValue(x, uri, null); } else if (type == typeof(string)) { prop.SetValue(x, value, null); } else if (type == typeof(DateTime)) { if (DateFormat.HasValue()) { value = DateTime.ParseExact(value.ToString(), DateFormat, Culture); } else { value = DateTime.Parse(value.ToString(), Culture); } prop.SetValue(x, value, null); } else if (type == typeof(DateTimeOffset)) { var toConvert = value.ToString(); if (!string.IsNullOrEmpty(toConvert)) { DateTimeOffset deserialisedValue; try { deserialisedValue = XmlConvert.ToDateTimeOffset(toConvert); prop.SetValue(x, deserialisedValue, null); } catch (Exception) { object result; if (TryGetFromString(toConvert, out result, type)) { prop.SetValue(x, result, null); } else { //fallback to parse deserialisedValue = DateTimeOffset.Parse(toConvert); prop.SetValue(x, deserialisedValue, null); } } } } else if (type == typeof(Decimal)) { //Hack for non defined price if (value.Equals("")) { prop.SetValue(x, 0.0m, null); } else { value = Decimal.Parse(value.ToString(), Culture); prop.SetValue(x, value, null); } } else if (type == typeof(Guid)) { var raw = value.ToString(); value = string.IsNullOrEmpty(raw) ? Guid.Empty : new Guid(value.ToString()); prop.SetValue(x, value, null); } else if (type == typeof(TimeSpan)) { var timeSpan = XmlConvert.ToTimeSpan(value.ToString()); prop.SetValue(x, timeSpan, null); } else if (type.IsGenericType) { var t = type.GetGenericArguments()[0]; var list = (IList)Activator.CreateInstance(type); var container = GetElementByName(root, prop.Name.AsNamespaced(Namespace)); if (container.HasElements) { var first = container.Elements().FirstOrDefault(); var elements = container.Elements(first.Name); PopulateListFromElements(t, elements, list); } prop.SetValue(x, list, null); } else if (type.IsSubclassOfRawGeneric(typeof(List <>))) { // handles classes that derive from List<T> // e.g. a collection that also has attributes var list = HandleListDerivative(x, root, prop.Name, type); prop.SetValue(x, list, null); } else { //fallback to type converters if possible object result; if (TryGetFromString(value.ToString(), out result, type)) { prop.SetValue(x, result, null); } else { // nested property classes if (root != null) { var element = GetElementByName(root, name); if (element != null) { var item = CreateAndMap(type, element); prop.SetValue(x, item, null); } } } } } }
/// <summary> /// Puts a local notification to show calendar card /// </summary> /// <param name="dataItem">Data item.</param> private async Task UpdateNotificationForDataItem(IDataItem dataItem) { if (Log.IsLoggable(Constants.TAG, LogPriority.Verbose)) { Log.Verbose(Constants.TAG, "Updating notification for IDataItem"); } DataMapItem mapDataItem = DataMapItem.FromDataItem(dataItem); DataMap data = mapDataItem.DataMap; String description = data.GetString(Constants.DESCRIPTION); if (TextUtils.IsEmpty(description)) { description = ""; } else { // Add a space between the description and the time of the event description += " "; } String contentText; if (data.GetBoolean(Constants.ALL_DAY)) { contentText = GetString(Resource.String.desc_all_day, description); } else { String startTime = DateFormat.GetTimeFormat(this).Format(new Date(data.GetLong(Constants.BEGIN))); String endTime = DateFormat.GetTimeFormat(this).Format(new Date(data.GetLong(Constants.END))); contentText = GetString(Resource.String.desc_time_period, description, startTime, endTime); } Intent deleteOperation = new Intent(this, typeof(DeleteService)); // Use a unique identifier for the delete action. String deleteAction = "action_delete" + dataItem.Uri.ToString() + sNotificationId; deleteOperation.SetAction(deleteAction); deleteOperation.SetData(dataItem.Uri); PendingIntent deleteIntent = PendingIntent.GetService(this, 0, deleteOperation, PendingIntentFlags.OneShot); PendingIntent silentDeleteIntent = PendingIntent.GetService(this, 1, deleteOperation.PutExtra(Constants.EXTRA_SILENT, true), PendingIntentFlags.OneShot); Notification.Builder notificationBuilder = new Notification.Builder(this) .SetContentTitle(data.GetString(Constants.TITLE)) .SetContentText(contentText) .SetSmallIcon(Resource.Drawable.ic_launcher) .AddAction(Resource.Drawable.ic_menu_delete, GetText(Resource.String.delete), deleteIntent) .SetDeleteIntent(silentDeleteIntent) .SetLocalOnly(true) .SetPriority((int)NotificationPriority.Min); // Set the event owner's profile picture as the notification background Asset asset = data.GetAsset(Constants.PROFILE_PIC); if (asset != null) { if (mGoogleApiClient.IsConnected) { var assetFdResult = await WearableClass.DataApi.GetFdForAssetAsync(mGoogleApiClient, asset); if (assetFdResult.Status.IsSuccess) { Bitmap profilePic = BitmapFactory.DecodeStream(assetFdResult.InputStream); notificationBuilder.Extend(new Notification.WearableExtender().SetBackground(profilePic)); } else if (Log.IsLoggable(Constants.TAG, LogPriority.Debug)) { Log.Debug(Constants.TAG, "asset fetch failed with StatusCode: " + assetFdResult.Status.StatusCode); } } else { Log.Error(Constants.TAG, "Failed to set notification background - Client disconnected from Google Play Services"); } Notification card = notificationBuilder.Build(); (GetSystemService(Context.NotificationService).JavaCast <NotificationManager>()).Notify(sNotificationId, card); sNotificationIdByDataItemUri.Add(dataItem.Uri, sNotificationId++); } }
public static string FormatDateToString(object xDateTime, DateFormat xDateFormat, MutiLanguage.Languages lang) { return FormatDateTimeToString(Convert.ToDateTime(xDateTime), xDateFormat, lang); }
public static string FormatDateTimeToString(DateTime xDateTime, DateFormat xDateFormat, MutiLanguage.Languages lang) { if (xDateTime == null || Convert.ToDateTime(xDateTime) == DateTime.MinValue) return ""; string langstr = MutiLanguage.EnumToString(lang); //System.Resources.ResourceManager rm = new System.Resources.ResourceManager(typeof(Resources.Date)); //System.Resources.ResourceSet rs = rm.GetResourceSet(new System.Globalization.CultureInfo(langstr), false, false); //return xDateTime.ToString(rs.GetString(xDateFormat.ToString()), System.Globalization.DateTimeFormatInfo.InvariantInfo); return xDateTime.ToString(Resources.Date.ResourceManager.GetString(xDateFormat.ToString(), new System.Globalization.CultureInfo(langstr)), System.Globalization.DateTimeFormatInfo.InvariantInfo); }
public static DateTime ConvertDate(string xDateString, DateFormat xDateFormat) { return ConvertDate(xDateString, xDateFormat, false); }
private void OnColumnDateFormatChanged(object sender, EventArgs e) { DateFormat = _column.DateFormat; }
public string ToString(DateFormat format) { return(CalendarCulture.ToString(this, format)); }
public HttpDateGenerator() : base() { this.dateformat = new SimpleDateFormat(PatternRfc1123, CultureInfo.InvariantCulture ); this.dateformat.SetTimeZone(Gmt); }
/// <summary> /// Constructs a <see cref="NumberDateFormat"/> object using the given <paramref name="dateStyle"/>, /// <paramref name="timeStyle"/>, and <paramref name="culture"/>. /// </summary> public NumberDateFormat(DateFormat dateStyle, DateFormat timeStyle, CultureInfo culture) : base(culture) { this.dateStyle = dateStyle; this.timeStyle = timeStyle; }
public Builder SetDateFormat(DateFormat dateFormat) { DateFormat = dateFormat; return(this); }
public void FormatDateTime(DateTime expression, DateFormat format, string expected) { Assert.Equal(expected, Strings.FormatDateTime(expression, format)); }
private static string MakeCommitVersionDetails(PackageUpdateSet updates) { var versionsInUse = updates.CurrentPackages .Select(u => u.Version) .Distinct() .ToList(); var oldVersions = versionsInUse .Select(v => CodeQuote(v.ToString())) .ToList(); var minOldVersion = versionsInUse.Min(); var newVersion = CodeQuote(updates.SelectedVersion.ToString()); var packageId = CodeQuote(updates.SelectedId); var changeLevel = ChangeLevel(minOldVersion, updates.SelectedVersion); var builder = new StringBuilder(); if (oldVersions.Count == 1) { builder.AppendLine($"NuKeeper has generated a {changeLevel} update of {packageId} to {newVersion} from {oldVersions.JoinWithCommas()}"); } else { builder.AppendLine($"NuKeeper has generated a {changeLevel} update of {packageId} to {newVersion}"); builder.AppendLine($"{oldVersions.Count} versions of {packageId} were found in use: {oldVersions.JoinWithCommas()}"); } if (updates.Selected.Published.HasValue) { var packageWithVersion = CodeQuote(updates.SelectedId + " " + updates.SelectedVersion); var pubDateString = CodeQuote(DateFormat.AsUtcIso8601(updates.Selected.Published)); var pubDate = updates.Selected.Published.Value.UtcDateTime; var ago = TimeSpanFormat.Ago(pubDate, DateTime.UtcNow); builder.AppendLine($"{packageWithVersion} was published at {pubDateString}, {ago}"); } var highestVersion = updates.Packages.Major?.Identity.Version; if (highestVersion != null && (highestVersion > updates.SelectedVersion)) { LogHighestVersion(updates, highestVersion, builder); } builder.AppendLine(); var updateOptS = (updates.CurrentPackages.Count > 1) ? "s" : string.Empty; builder.AppendLine($"### {updates.CurrentPackages.Count} project update{updateOptS}:"); builder.AppendLine("| Project | Package | From | To |"); builder.AppendLine("|:----------|:----------|-------:|-----:|"); foreach (var current in updates.CurrentPackages) { string line; if (SourceIsPublicNuget(updates.Selected.Source.SourceUri)) { line = $"| {CodeQuote(current.Path.RelativePath)} | {CodeQuote(updates.SelectedId)} | {NuGetVersionPackageLink(current.Identity)} | {NuGetVersionPackageLink(updates.Selected.Identity)} |"; builder.AppendLine(line); continue; } line = $"| {CodeQuote(current.Path.RelativePath)} | {CodeQuote(updates.SelectedId)} | {current.Version.ToString()} | {updates.SelectedVersion.ToString()} |"; builder.AppendLine(line); } return(builder.ToString()); }
/// <summary> /// Json response converts to its expected data type and culture /// </summary> /// <param name="typeInfo"></param> /// <param name="value"></param> /// <returns></returns> private object ConvertValue(TypeInfo typeInfo, object value) { string stringValue = Convert.ToString(value, Culture); // check for nullable and extract underlying type if (typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition() == typeof(Nullable <>)) { // Since the type is nullable and no value is provided return null if (string.IsNullOrEmpty(stringValue)) { return(null); } typeInfo = typeInfo.GetGenericArguments()[0].GetTypeInfo(); } if (typeInfo.AsType() == typeof(object)) { if (value == null) { return(null); } typeInfo = value.GetType().GetTypeInfo(); } var type = typeInfo.AsType(); if (typeInfo.IsPrimitive) { return(value.ChangeType(type, Culture)); } if (typeInfo.IsEnum) { return(type.FindEnumValue(stringValue, Culture)); } if (type == typeof(Uri)) { return(new Uri(stringValue, UriKind.RelativeOrAbsolute)); } if (type == typeof(string)) { return(stringValue); } if (type == typeof(DateTime) || type == typeof(DateTimeOffset)) { DateTime dt; if (DateFormat.HasValue()) { dt = DateTime.ParseExact(stringValue, DateFormat, Culture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); } else { // try parsing instead dt = stringValue.ParseJsonDate(this.Culture); } } else if (type.GetTypeInfo().IsGenericType) { Type genericTypeDef = type.GetGenericTypeDefinition(); if (genericTypeDef == typeof(IEnumerable <>)) { Type itemType = typeInfo.GetGenericArguments()[0]; Type listType = typeof(List <>).MakeGenericType(itemType); return(BuildList(listType, value)); } if (genericTypeDef == typeof(List <>)) { return(BuildList(type, value)); } if (genericTypeDef == typeof(Dictionary <,>)) { return(BuildDictionary(type, value)); } // nested property classes return(CreateAndMap(type, value)); } else { // nested property classes return(CreateAndMap(type, value)); } return(null); }
public static FuzzyDateTime ParseDateTime(string input, DateFormat dateFormat) { // Packed format DateTime dateTime; if (DateTime.TryParseExact(input, "s", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dateTime)) { return new FuzzyDateTime(dateTime, true); } // "Today" if (string.Compare(input, "today", StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(input, "tod", StringComparison.OrdinalIgnoreCase) == 0) { return new FuzzyDateTime(DateTime.Today, false); } // "Tomorrow" if (string.Compare(input, "tomorrow", StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(input, "tom", StringComparison.OrdinalIgnoreCase) == 0) { return new FuzzyDateTime(DateTime.Today.AddDays(1), false); } // "25 Apr", or "Apr 25" string[] formats1 = { "dd MMM", // 25 Apr "MMM dd", // Apr 25 }; if (DateTime.TryParseExact(input, formats1, System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None, out dateTime)) { if (dateTime < DateTime.Today) dateTime = dateTime.AddYears(1); return new FuzzyDateTime(dateTime, false); } // "2008/04/25" or "2008-04-25" string[] formats2 = { "yyyy/MM/dd", // 2008/04/25 "yyyy-MM-dd" // 2008-04-25 }; if (DateTime.TryParseExact(input, formats2, System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None, out dateTime)) { return new FuzzyDateTime(dateTime, false); } // American and European date formats if (dateFormat == DateFormat.American) { if (DateTime.TryParseExact(input, "MM/dd/yy", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None, out dateTime)) { return new FuzzyDateTime(dateTime, false); } if (DateTime.TryParseExact(input, "MM/dd/yyyy", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None, out dateTime)) { return new FuzzyDateTime(dateTime, false); } } else if (dateFormat == DateFormat.European) { if (DateTime.TryParseExact(input, "dd/MM/yy", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None, out dateTime)) { return new FuzzyDateTime(dateTime, false); } if (DateTime.TryParseExact(input, "dd/MM/yyyy", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None, out dateTime)) { return new FuzzyDateTime(dateTime, false); } } // "25th" Match match = Regex.Match(input, @"^\s*(?<day>\d\d?)(st|nd|rd|th)\s*$"); if (match.Success) { // "25th" var today = DateTime.Today; var day = int.Parse(match.Groups["day"].Value); var result = new DateTime(today.Year, today.Month, day); if (day < today.Day) result = result.AddMonths(1); return new FuzzyDateTime(result, false); } // "End of month" if (Regex.IsMatch(input, @"^\s*end\s+of\s+month\s*$", RegexOptions.IgnoreCase)) { var today = DateTime.Today; var firstDayOfMonth = new DateTime(today.Year, today.Month, 1); return new FuzzyDateTime(firstDayOfMonth.AddMonths(1).AddDays(-1), false); } // "Friday", or "Next Friday" match = Regex.Match(input, @"^\s*(?<next>next\s+)?" + DaysOfWeekPattern + @"\s*$", RegexOptions.IgnoreCase); if (match.Success) { var targetDayOfWeek = GetDayOfWeek(match.Groups["dayofweek"].Value); var result = DateTime.Today; while (result.DayOfWeek != targetDayOfWeek) result = result.AddDays(1); if (match.Groups["next"].Success) // If "next", add a week. result = result.AddDays(7); return new FuzzyDateTime(result, false); } // "Fri at 7pm" or "Fri@7pm" match = Regex.Match(input, @"^\s*" + DaysOfWeekPattern + @"((\s*@\s*)|(\s+at\s+))" + TimePattern + @"\s*$", RegexOptions.IgnoreCase); if (match.Success) { var targetDayOfWeek = GetDayOfWeek(match.Groups["dayofweek"].Value); var result = DateTime.Today; while (result.DayOfWeek != targetDayOfWeek) result = result.AddDays(1); int hours = int.Parse(match.Groups["hours"].Value); result = result.AddHours(hours); if (match.Groups["minutes"].Success) { int minutes = int.Parse(match.Groups["minutes"].Value); result = result.AddMinutes(minutes); } if (match.Groups["ampm"].Success && string.Compare(match.Groups["ampm"].Value, "pm", StringComparison.OrdinalIgnoreCase) == 0) { result = result.AddHours(12); } return new FuzzyDateTime(result, true); } // "6pm" or "18:00" match = Regex.Match(input, @"^\s*" + TimePattern + @"\s*$", RegexOptions.IgnoreCase); if (match.Success) { var result = DateTime.Today; int hours = int.Parse(match.Groups["hours"].Value); result = result.AddHours(hours); if (match.Groups["minutes"].Success) { int minutes = int.Parse(match.Groups["minutes"].Value); result = result.AddMinutes(minutes); } if (match.Groups["ampm"].Success && string.Compare(match.Groups["ampm"].Value, "pm", StringComparison.OrdinalIgnoreCase) == 0) { result = result.AddHours(12); } if (result < DateTime.Now) result = result.AddDays(1); return new FuzzyDateTime(result, true); } // "20 minutes" match = Regex.Match(input, @"^\s*(?<num>\d+)\s*(m|mn|mins?|minutes?)\s*$", RegexOptions.IgnoreCase); if (match.Success) { int num = int.Parse(match.Groups["num"].Value); var result = DateTime.Now; result = result.AddMinutes(num); return new FuzzyDateTime(result, true); } // "5 hours" match = Regex.Match(input, @"^\s*(?<num>\d+)\s*(h|hours?|hrs?)\s*$", RegexOptions.IgnoreCase); if (match.Success) { int num = int.Parse(match.Groups["num"].Value); var result = DateTime.Now; result = result.AddHours(num); return new FuzzyDateTime(result, true); } // "2 days", or "2 days of today" match = Regex.Match(input, @"^\s*(?<num>\d+)\s*(d|days?)(\s+of\s+today)?\s*$", RegexOptions.IgnoreCase); if (match.Success) { int num = int.Parse(match.Groups["num"].Value); var result = DateTime.Today; result = result.AddDays(num); return new FuzzyDateTime(result, false); } // "3 weeks" match = Regex.Match(input, @"^\s*(?<num>\d+)\s*(w|weeks?)(\s+of\s+today)?\s*$", RegexOptions.IgnoreCase); if (match.Success) { int num = int.Parse(match.Groups["num"].Value); var result = DateTime.Today; result = result.AddDays(num * 7); return new FuzzyDateTime(result, false); } // "1 month" match = Regex.Match(input, @"^\s*(?<num>\d+)\s*(m|months?)(\s+of\s+today)?\s*$", RegexOptions.IgnoreCase); if (match.Success) { int num = int.Parse(match.Groups["num"].Value); var result = DateTime.Today; result = result.AddMonths(num); return new FuzzyDateTime(result, false); } // "1 year" match = Regex.Match(input, @"^\s*(?<num>\d+)\s*(y|years?)(\s+of\s+today)?\s*$", RegexOptions.IgnoreCase); if (match.Success) { int num = int.Parse(match.Groups["num"].Value); var result = DateTime.Today; result = result.AddYears(num); return new FuzzyDateTime(result, false); } // "now" match = Regex.Match(input, @"^now$", RegexOptions.IgnoreCase); if (match.Success) { var result = DateTime.Now; return new FuzzyDateTime(result, true); } throw new ArgumentException(); }
/// <summary>Returns a date/time format instance for the given styles.</summary> /// <remarks>Returns a date/time format instance for the given styles.</remarks> /// <param name="dateStyle"> /// the date style as specified in /// <see cref="Sharpen.DateFormat.GetDateTimeInstance(int, int)">Sharpen.DateFormat.GetDateTimeInstance(int, int) /// </see> /// </param> /// <param name="timeStyle"> /// the time style as specified in /// <see cref="Sharpen.DateFormat.GetDateTimeInstance(int, int)">Sharpen.DateFormat.GetDateTimeInstance(int, int) /// </see> /// </param> /// <returns>the date format</returns> /// <since>2.0</since> public virtual DateFormat GetDateTimeInstance(int dateStyle, int timeStyle) { return(DateFormat.GetDateTimeInstance(dateStyle, timeStyle)); }
/// <summary> /// ����ʱ�������ת��Ϊָ����ʽ���ַ��� /// </summary> /// <param name="xDateTime"></param> /// <param name="xDateFormat"></param> /// <param name="isMutiLang"></param> /// <returns></returns> public static string FormatDateTimeToString(DateTime xDateTime, DateFormat xDateFormat, bool isMutiLang) { return FormatDateTimeToString(xDateTime, xDateFormat.ToString(), isMutiLang); }
private bool Form_LoadData(object sender, object data) { if (data == null) { return(false); } if (!(data is OpenPositionItem)) { return(false); } _originOpenItem = data as OpenPositionItem; if (_originOpenItem == null) { return(false); } // this.tbPortfolio.Text = _originOpenItem.PortfolioName; this.tbTemlate.Text = string.Format("{0}-{1}", _originOpenItem.TemplateId, _originOpenItem.TemplateName); this.tbFutures.Text = _originOpenItem.FuturesContract; this.tbCopies.Text = string.Format("{0}", _originOpenItem.Copies); this.tbCopies.Enabled = false; this.tbBias.Text = "0"; DateTime now = DateTime.Now; DateTime startDate = new DateTime(now.Year, now.Month, now.Day, 9, 15, 0); DateTime endDate = new DateTime(now.Year, now.Month, now.Day, 15, 15, 0); this.tbStartDate.Text = DateFormat.Format(startDate, ConstVariable.DateFormat1); this.tbEndDate.Text = DateFormat.Format(endDate, ConstVariable.DateFormat1); this.tbStartTime.Text = DateFormat.Format(startDate, ConstVariable.TimeFormat1); this.tbEndTime.Text = DateFormat.Format(endDate, ConstVariable.TimeFormat1); //Initialize the instancecode var instances = _tradeInstanceBLL.GetAllInstance(); var targetInstances = instances.Where(p => p.MonitorUnitId == _originOpenItem.MonitorId && p.TemplateId == _originOpenItem.TemplateId).ToList(); ComboOption comboOption = new ComboOption { Items = new List <ComboOptionItem>() }; if (targetInstances == null || targetInstances.Find(p => p.InstanceCode.Equals(_originOpenItem.InstanceCode)) == null) { ComboOptionItem currentItem = new ComboOptionItem { Id = _originOpenItem.InstanceCode, Name = _originOpenItem.InstanceCode }; comboOption.Items.Add(currentItem); } if (targetInstances != null && targetInstances.Count > 0) { foreach (var instance in targetInstances) { ComboOptionItem item = new ComboOptionItem { Id = instance.InstanceCode, Name = instance.InstanceCode }; comboOption.Items.Add(item); } } ComboBoxUtil.SetComboBox(this.cbInstanceCode, comboOption); ComboBoxUtil.SetComboBoxSelect(this.cbInstanceCode, _originOpenItem.InstanceCode); return(true); }
/// <summary> /// Get DateTime,the time only can be /// </summary> /// <param name="xDateString"></param> /// <param name="xDateFormat"></param> /// <param name="xdaySegment"></param> /// <returns></returns> public static DateTime ConvertDate(string xDateString, DateFormat xDateFormat, DaySegment xdaySegment) { return GetAbsDate(ConvertDate(xDateString, xDateFormat), xdaySegment); }
public void LoadFromFile(IniFile ini) { if (ini == null) { throw new ArgumentNullException("ini"); } int optsVersion = ini.ReadInteger("Common", "OptsVersion", 0); fDefNameFormat = (NameFormat)ini.ReadInteger("Common", "DefNameFormat", 0); fDefDateFormat = (DateFormat)ini.ReadInteger("Common", "DefDateFormat", 0); fLastDir = ini.ReadString("Common", "LastDir", ""); fPlacesWithAddress = ini.ReadBool("Common", "PlacesWithAddress", false); fShowTips = ini.ReadBool("Common", "ShowTips", true); fInterfaceLang = (ushort)ini.ReadInteger("Common", "InterfaceLang", 0); fFileBackup = (FileBackup)ini.ReadInteger("Common", "FileBackup", 0); fShowDatesCalendar = ini.ReadBool("Common", "ShowDatesCalendar", false); fShowDatesSign = ini.ReadBool("Common", "ShowDatesSigns", false); fRemovableMediaWarning = ini.ReadBool("Common", "RemovableMediaWarning", true); fLoadRecentFiles = ini.ReadBool("Common", "LoadRecentFiles", true); fEmbeddedMediaPlayer = ini.ReadBool("Common", "EmbeddedMediaPlayer", true); fAllowMediaStoreReferences = ini.ReadBool("Common", "AllowMediaStoreReferences", false); fAutoCheckUpdates = ini.ReadBool("Common", "AutoCheckUpdates", true); fAutoSortChildren = ini.ReadBool("Common", "AutoSortChildren", true); fAutoSortSpouses = ini.ReadBool("Common", "AutoSortSpouses", false); fCharsetDetection = ini.ReadBool("Common", "CharsetDetection", false); fAutosave = ini.ReadBool("Common", "Autosave", false); fAutosaveInterval = ini.ReadInteger("Common", "AutosaveInterval", 10); fExtendedNames = ini.ReadBool("Common", "ExtendedNames", false); fWomanSurnameFormat = (WomanSurnameFormat)ini.ReadInteger("Common", "WomanSurnameFormat", 0); fGeocoder = ini.ReadString("Common", "Geocoder", "Google"); int kl = ini.ReadInteger("Common", "KeyLayout", AppHost.Instance.GetKeyLayout()); AppHost.Instance.SetKeyLayout(kl); fTreeChartOptions.LoadFromFile(ini); fPedigreeOptions.LoadFromFile(ini); fProxy.LoadFromFile(ini); int cnt = ini.ReadInteger("NameFilters", "Count", 0); for (int i = 0; i < cnt; i++) { string st = ini.ReadString("NameFilters", "Filter_" + i.ToString(), ""); if (st != "") { fNameFilters.Add(st); } } cnt = ini.ReadInteger("ResidenceFilters", "Count", 0); for (int i = 0; i < cnt; i++) { fResidenceFilters.Add(ini.ReadString("ResidenceFilters", "Filter_" + i.ToString(), "")); } cnt = ini.ReadInteger("EventFilters", "Count", 0); for (int i = 0; i < cnt; i++) { fEventFilters.Add(ini.ReadString("EventFilters", "EventVal_" + i.ToString(), "")); } LoadMRUFromFile(ini, fMRUFiles); cnt = ini.ReadInteger("Relations", "Count", 0); for (int i = 0; i < cnt; i++) { fRelations.Add(ini.ReadString("Relations", "Relation_" + i.ToString(), "")); } fIndividualListColumns.LoadFromFile(ini, "PersonsColumns"); fListHighlightUnmarriedPersons = ini.ReadBool("ListPersons", "HighlightUnmarried", false); fListHighlightUnparentedPersons = ini.ReadBool("ListPersons", "HighlightUnparented", false); fMWinRect.Left = ini.ReadInteger("Common", "MWinL", -1); fMWinRect.Top = ini.ReadInteger("Common", "MWinT", -1); fMWinRect.Right = ini.ReadInteger("Common", "MWinW", -1); fMWinRect.Bottom = ini.ReadInteger("Common", "MWinH", -1); fMWinState = (WindowState)((uint)ini.ReadInteger("Common", "MWinState", 0)); cnt = ini.ReadInteger("LastBases", "Count", 0); for (int i = 0; i < cnt; i++) { string st = ini.ReadString("LastBases", "LB" + i.ToString(), ""); AddLastBase(st); } fCircleChartOptions.LoadFromFile(ini); fListOptions.LoadFromFile(ini); LoadPluginsFromFile(ini); }
public static string FormatDateToString(object xDateTime, DateFormat xDateFormat) { return FormatDateTimeToString(Convert.ToDateTime(xDateTime), xDateFormat, false); }
static string ProjectLastOpenedString(ProjectData project) { return(project.LastOpened.HasValue ? DateFormat.PeriodBetween(DateTime.Now, project.LastOpened.Value) : "N/A"); }
public override void BeforeClass() { base.BeforeClass(); ANALYZER = new MockAnalyzer(Random); qp = new StandardQueryParser(ANALYZER); IDictionary <string, /*Number*/ object> randomNumberMap = new JCG.Dictionary <string, object>(); /*SimpleDateFormat*/ string dateFormat; long randomDate; bool dateFormatSanityCheckPass; int count = 0; do { if (count > 100) { fail("This test has problems to find a sane random DateFormat/NumberFormat. Stopped trying after 100 iterations."); } dateFormatSanityCheckPass = true; LOCALE = RandomCulture(Random); TIMEZONE = RandomTimeZone(Random); DATE_STYLE = randomDateStyle(Random); TIME_STYLE = randomDateStyle(Random); //// assumes localized date pattern will have at least year, month, day, //// hour, minute //dateFormat = (SimpleDateFormat)DateFormat.getDateTimeInstance( // DATE_STYLE, TIME_STYLE, LOCALE); //// not all date patterns includes era, full year, timezone and second, //// so we add them here //dateFormat.applyPattern(dateFormat.toPattern() + " G s Z yyyy"); //dateFormat.setTimeZone(TIMEZONE); // assumes localized date pattern will have at least year, month, day, // hour, minute DATE_FORMAT = new NumberDateFormat(DATE_STYLE, TIME_STYLE, LOCALE) { TimeZone = TIMEZONE }; // not all date patterns includes era, full year, timezone and second, // so we add them here DATE_FORMAT.SetDateFormat(DATE_FORMAT.GetDateFormat() + " g s z yyyy"); dateFormat = DATE_FORMAT.GetDateFormat(); do { randomDate = Random.nextLong(); // prune date value so it doesn't pass in insane values to some // calendars. randomDate = randomDate % 3400000000000L; // truncate to second randomDate = (randomDate / 1000L) * 1000L; // only positive values randomDate = Math.Abs(randomDate); } while (randomDate == 0L); dateFormatSanityCheckPass &= checkDateFormatSanity(dateFormat, randomDate); dateFormatSanityCheckPass &= checkDateFormatSanity(dateFormat, 0); dateFormatSanityCheckPass &= checkDateFormatSanity(dateFormat, -randomDate); count++; } while (!dateFormatSanityCheckPass); //NUMBER_FORMAT = NumberFormat.getNumberInstance(LOCALE); //NUMBER_FORMAT.setMaximumFractionDigits((Random().nextInt() & 20) + 1); //NUMBER_FORMAT.setMinimumFractionDigits((Random().nextInt() & 20) + 1); //NUMBER_FORMAT.setMaximumIntegerDigits((Random().nextInt() & 20) + 1); //NUMBER_FORMAT.setMinimumIntegerDigits((Random().nextInt() & 20) + 1); NUMBER_FORMAT = new NumberFormat(LOCALE); double randomDouble; long randomLong; int randomInt; float randomFloat; while ((randomLong = Convert.ToInt64(NormalizeNumber(Math.Abs(Random.nextLong())) )) == 0L) { ; } while ((randomDouble = Convert.ToDouble(NormalizeNumber(Math.Abs(Random.NextDouble())) )) == 0.0) { ; } while ((randomFloat = Convert.ToSingle(NormalizeNumber(Math.Abs(Random.nextFloat())) )) == 0.0f) { ; } while ((randomInt = Convert.ToInt32(NormalizeNumber(Math.Abs(Random.nextInt())))) == 0) { ; } randomNumberMap.Put(NumericType.INT64.ToString(), randomLong); randomNumberMap.Put(NumericType.INT32.ToString(), randomInt); randomNumberMap.Put(NumericType.SINGLE.ToString(), randomFloat); randomNumberMap.Put(NumericType.DOUBLE.ToString(), randomDouble); randomNumberMap.Put(DATE_FIELD_NAME, randomDate); RANDOM_NUMBER_MAP = randomNumberMap.AsReadOnly(); directory = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random, directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)) .SetMaxBufferedDocs(TestUtil.NextInt32(Random, 50, 1000)) .SetMergePolicy(NewLogMergePolicy())); Document doc = new Document(); IDictionary <String, NumericConfig> numericConfigMap = new JCG.Dictionary <String, NumericConfig>(); IDictionary <String, Field> numericFieldMap = new JCG.Dictionary <String, Field>(); qp.NumericConfigMap = (numericConfigMap); foreach (NumericType type in Enum.GetValues(typeof(NumericType))) { if (type == NumericType.NONE) { continue; } numericConfigMap.Put(type.ToString(), new NumericConfig(PRECISION_STEP, NUMBER_FORMAT, type)); FieldType ft2 = new FieldType(Int32Field.TYPE_NOT_STORED); ft2.NumericType = (type); ft2.IsStored = (true); ft2.NumericPrecisionStep = (PRECISION_STEP); ft2.Freeze(); Field field; switch (type) { case NumericType.INT32: field = new Int32Field(type.ToString(), 0, ft2); break; case NumericType.SINGLE: field = new SingleField(type.ToString(), 0.0f, ft2); break; case NumericType.INT64: field = new Int64Field(type.ToString(), 0L, ft2); break; case NumericType.DOUBLE: field = new DoubleField(type.ToString(), 0.0, ft2); break; default: fail(); field = null; break; } numericFieldMap.Put(type.ToString(), field); doc.Add(field); } numericConfigMap.Put(DATE_FIELD_NAME, new NumericConfig(PRECISION_STEP, DATE_FORMAT, NumericType.INT64)); FieldType ft = new FieldType(Int64Field.TYPE_NOT_STORED); ft.IsStored = (true); ft.NumericPrecisionStep = (PRECISION_STEP); Int64Field dateField = new Int64Field(DATE_FIELD_NAME, 0L, ft); numericFieldMap.Put(DATE_FIELD_NAME, dateField); doc.Add(dateField); foreach (NumberType numberType in Enum.GetValues(typeof(NumberType))) { setFieldValues(numberType, numericFieldMap); if (VERBOSE) { Console.WriteLine("Indexing document: " + doc); } writer.AddDocument(doc); } reader = writer.GetReader(); searcher = NewSearcher(reader); writer.Dispose(); }
/// <summary> /// Update user /// </summary> /// <param name="newEmail"> /// New email /// </param> /// <param name="newFullName"> /// New name /// </param> /// <param name="newPassword"> /// New password /// </param> /// <param name="newTimeZone"> /// New timezone /// </param> /// <param name="newDateFormat"> /// New dateformat /// </param> /// <param name="newTimeFormat"> /// New timeformat /// </param> /// <param name="newStartPage"> /// New startpage /// </param> public void UpdateUser( string newEmail, string newFullName, string newPassword, string newTimeZone, DateFormat? newDateFormat, TimeFormat? newTimeFormat, StartPage? newStartPage) { this.CheckLoginStatus(); Uri uri = Core.ConstructUri( "updateUser?", string.Format( "token={0}&" + "email={1}&" + "full_name={2}&" + "password={3}&" + "timezone={4}&" + "date_format={5}&" + "time_format={6}&" + "start_page={7}", this.ApiToken, newEmail, newFullName, newPassword, newTimeZone, newDateFormat, newTimeFormat, newStartPage), true); string jsonResponse = Core.GetJsonData(uri); switch (jsonResponse) { case "\"ERROR_PASSWORD_TOO_SHORT\"": throw new UpdateUserException( "The password provided is too short. It must be at least 5 characters long."); case "\"ERROR_EMAIL_FOUND\"": throw new UpdateUserException( "The e-mail address provided has already been registered with Todoist with another account."); } this.jsonData = jsonResponse; this.AnalyseJson(); }
private static string Now() { return(DateFormat.AsUtcIso8601(DateTimeOffset.Now)); }
/// <summary> /// Resets all properties, because there is no real logging out from Todoist.com /// </summary> public void LogOff() { this.id = 0; this.email = string.Empty; this.fullName = string.Empty; this.apiToken = string.Empty; this.startPage = new StartPage(); this.timeZone = null; this.timeZoneOffset = new TimeZoneOffset(); this.timeFormat = new TimeFormat(); this.dateFormat = 0; this.sortOrder = SortOrder.OldestDatesFirst; this.notifoAccount = string.Empty; this.mobileNumber = string.Empty; this.mobileHost = string.Empty; this.premiumUntil = string.Empty; this.defaultReminder = new DefaultReminder(); this.jsonData = string.Empty; }
private static string FormatDate(DateTime date, DateFormat dateFormat) { var stringFormat = DateFormatToDateTimeFormatString[dateFormat]; return(date.ToString(stringFormat)); }
public static string FormatRecurrence(Recurrence recurrence, DateFormat dateFormat) { return FormatRecurrence(recurrence.Repeat, recurrence.IsEvery, dateFormat); }
private void btnSimpleList_Click(object sender, EventArgs e) { Report report = new Report(); // load nwind database DataSet dataSet = new DataSet(); dataSet.ReadXml(GetReportsFolder() + "nwind.xml"); // register all data tables and relations report.RegisterData(dataSet); // enable the "Employees" table to use it in the report report.GetDataSource("Employees").Enabled = true; // add report page ReportPage page = new ReportPage(); report.Pages.Add(page); // always give names to objects you create. You can use CreateUniqueName method to do this; // call it after the object is added to a report. page.CreateUniqueName(); // create title band page.ReportTitle = new ReportTitleBand(); // native FastReport unit is screen pixel, use conversion page.ReportTitle.Height = Units.Centimeters * 1; page.ReportTitle.CreateUniqueName(); // create title text TextObject titleText = new TextObject(); titleText.Parent = page.ReportTitle; titleText.CreateUniqueName(); titleText.Bounds = new RectangleF(Units.Centimeters * 5, 0, Units.Centimeters * 10, Units.Centimeters * 1); titleText.Font = new Font("Arial", 14, FontStyle.Bold); titleText.Text = "Employees"; titleText.HorzAlign = HorzAlign.Center; // create data band DataBand dataBand = new DataBand(); page.Bands.Add(dataBand); dataBand.CreateUniqueName(); dataBand.DataSource = report.GetDataSource("Employees"); dataBand.Height = Units.Centimeters * 0.5f; // create two text objects with employee's name and birth date TextObject empNameText = new TextObject(); empNameText.Parent = dataBand; empNameText.CreateUniqueName(); empNameText.Bounds = new RectangleF(0, 0, Units.Centimeters * 5, Units.Centimeters * 0.5f); empNameText.Text = "[Employees.FirstName] [Employees.LastName]"; TextObject empBirthDateText = new TextObject(); empBirthDateText.Parent = dataBand; empBirthDateText.CreateUniqueName(); empBirthDateText.Bounds = new RectangleF(Units.Centimeters * 5.5f, 0, Units.Centimeters * 3, Units.Centimeters * 0.5f); empBirthDateText.Text = "[Employees.BirthDate]"; // format value as date DateFormat format = new DateFormat(); format.Format = "MM/dd/yyyy"; empBirthDateText.Format = format; // run report designer report.Design(); }
public DateTimeStamp(DateFormat format, DateCorner corner, DateStyle style) { Format = format; Corner = corner; Style = style; }
/// <summary> /// The analyse json. /// </summary> private void AnalyseJson() { JObject o = JObject.Parse(this.JsonData); this.notifoAccount = (string)o.SelectToken("notifo"); this.apiToken = (string)o.SelectToken("api_token"); switch ((int)o.SelectToken("time_format")) { case 0: this.timeFormat = TimeFormat.TwentyFourHourClock; break; case 1: this.timeFormat = TimeFormat.TwelveHourClock; break; } switch ((int)o.SelectToken("sort_order")) { case 0: this.sortOrder = SortOrder.OldestDatesFirst; break; case 1: this.sortOrder = SortOrder.NewestDatesFirst; break; } this.fullName = (string)o.SelectToken("full_name"); this.mobileNumber = (string)o.SelectToken("mobile_number"); this.mobileHost = (string)o.SelectToken("mobile_host"); this.timeZone = (string)o.SelectToken("timezone"); this.id = (int)o.SelectToken("id"); switch ((int)o.SelectToken("date_format")) { case 0: this.dateFormat = DateFormat.DdMmYyyy; break; case 1: this.dateFormat = DateFormat.MmDdYyyy; break; } this.premiumUntil = (string)o.SelectToken("premium_until"); JToken timeZoneString = o.SelectToken("tz_offset"); this.timeZoneOffset = new TimeZoneOffset( timeZoneString.First.Value<string>(), timeZoneString.First.Next.Value<int>(), timeZoneString.First.Next.Next.Value<int>(), timeZoneString.First.Next.Next.Next.Value<bool>()); switch ((string)o.SelectToken("default_reminder")) { case "email": this.defaultReminder = DefaultReminder.Email; break; case "mobile": this.defaultReminder = DefaultReminder.Mobile; break; case "notifo": this.defaultReminder = DefaultReminder.Notifo; break; case "no_defalt": this.defaultReminder = DefaultReminder.NoDefault; break; } this.email = (string)o.SelectToken("email"); }
object ConvertValue(Type type, object value) { var stringValue = Convert.ToString(value, Culture); // check for nullable and extract underlying type if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>)) { // Since the type is nullable and no value is provided return null if (String.IsNullOrEmpty(stringValue)) { return(null); } type = type.GetGenericArguments()[0]; } if (type == typeof(Object) && value != null) { type = value.GetType(); } if (type.IsPrimitive) { return(value.ChangeType(type, Culture)); } if (type.IsEnum) { return(type.FindEnumValue(stringValue, Culture)); } if (type == typeof(Uri)) { return(new Uri(stringValue, UriKind.RelativeOrAbsolute)); } if (type == typeof(string)) { return(stringValue); } if (type == typeof(DateTime) || type == typeof(DateTimeOffset)) { DateTime dt; if (DateFormat.HasValue()) { dt = DateTime.ParseExact(stringValue, DateFormat, Culture); } else { // try parsing instead dt = stringValue.ParseJsonDate(Culture); } if (type == typeof(DateTime)) { return(dt); } if (type == typeof(DateTimeOffset)) { return((DateTimeOffset)dt); } } else if (type == typeof(Decimal)) { if (value is double) { return((decimal)((double)value)); } return(Decimal.Parse(stringValue, Culture)); } else if (type == typeof(byte[])) { return(ConvertByteArray(stringValue)); } else if (type == typeof(Guid)) { return(string.IsNullOrEmpty(stringValue) ? Guid.Empty : new Guid(stringValue)); } else if (type == typeof(TimeSpan)) { return(TimeSpan.Parse(stringValue)); } else if (type.IsGenericType) { var genericTypeDef = type.GetGenericTypeDefinition(); if (genericTypeDef == typeof(List <>)) { return(BuildList(type, value)); } if (genericTypeDef == typeof(Dictionary <,>)) { var keyType = type.GetGenericArguments()[0]; // only supports Dict<string, T>() if (keyType == typeof(string)) { return(BuildDictionary(type, value)); } } else { // nested property classes return(CreateAndMap(type, value)); } } else { // nested property classes return(CreateAndMap(type, value)); } return(null); }
public static Recurrence ParseRecurrence(string input, DateFormat dateFormat) { if (string.IsNullOrEmpty(input)) throw new ArgumentNullException(); int offset; bool isEvery; StringBuilder result = new StringBuilder(); input = input.ToLower(); string[] words = input.Split(' ', '\t'); if (string.Equals(words[0], "every")) { isEvery = true; DayOfWeek dayOfWeek; if (DateConverter.TryGetDayOfWeek(words[1], out dayOfWeek)) { // "Every Tuesday", or "Every Monday and Wednesday" result.Append("FREQ=WEEKLY;"); result.AppendFormat("BYDAY={0}", dayOfWeek.ToString().Substring(0, 2).ToUpper()); for (int i = 2; i < words.Length; i++) { if ((i % 2) == 0) { // Stop if we encounter an "until" or "for" clause. if (string.Equals(words[i], "until") || string.Equals(words[i], "for")) { offset = i; break; } if (!string.Equals(words[i], "and")) throw new ArgumentException(); } else { if (!DateConverter.TryGetDayOfWeek(words[i], out dayOfWeek)) throw new ArgumentException(); result.AppendFormat(",{0}", dayOfWeek.ToString().Substring(0, 2).ToUpper()); } } offset = words.Length; } else if (string.Equals(words[1], "weekday")) { // "Every weekday" result.Append("FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR"); offset = 2; } else if (string.Equals(words[1], "weekend")) { // "Every weekend" result.Append("FREQ=WEEKLY;BYDAY=SA,SU"); offset = 2; } else if (string.Equals(words[1], "day")) { // "Every day" result.Append("FREQ=DAILY;INTERVAL=1"); offset = 2; } else if (string.Equals(words[1], "week")) { // "Every week" result.Append("FREQ=WEEKLY;INTERVAL=1"); offset = 2; } else if (string.Equals(words[1], "month")) { // "Every month" result.Append("FREQ=MONTHLY;INTERVAL=1"); offset = 2; if (words.Length >= 4 && string.Equals(words[2], "on") && string.Equals(words[3], "the")) { if (words.Length == 4) throw new ArgumentException(); Match match = Regex.Match(words[4], @"(?<dayofmonth>[0-9]+)(st|nd|rd|th)"); if (match.Success) { int dayOfMonth = int.Parse(match.Groups["dayofmonth"].Value); if (words.Length == 5) { // "Every month on the 5th" result.AppendFormat(";BYMONTHDAY={0}", dayOfMonth); offset = 5; } else { // "Every month on the 2nd last Friday" or "Every month on the 3rd Tuesday" offset = 5; if (string.Equals(words[5], "last")) { result.AppendFormat(";BYDAY=-{0}", dayOfMonth); offset = 6; } if (words.Length <= offset) throw new ArgumentException(); if (!DateConverter.TryGetDayOfWeek(words[offset], out dayOfWeek)) throw new ArgumentException(); result.AppendFormat(";BYDAY={0}", dayOfWeek.ToString().Substring(0, 2).ToUpper()); offset += 1; } } else { if (string.Equals(words[4], "last")) { // "Every month on the last Friday" dayOfWeek = DateConverter.GetDayOfWeek(words[5]); result.AppendFormat(";BYDAY=-1{0}", dayOfWeek.ToString().Substring(0, 2).ToUpper()); offset = 6; } else { throw new ArgumentException(); } } } } else if (string.Equals(words[1], "year")) { // "Every year" result.Append("FREQ=YEARLY"); offset = 2; } else if (string.Equals(words[2], "days")) { // "Every 2 days" int interval = int.Parse(words[1]); result.AppendFormat("FREQ=DAILY;INTERVAL={0}", interval); offset = 3; } else if (string.Equals(words[2], "weeks")) { // "Every 2 weeks" int interval = int.Parse(words[1]); result.AppendFormat("FREQ=WEEKLY;INTERVAL={0}", interval); offset = 3; } else if (string.Equals(words[2], "months")) { // "Every 2 months" int interval = int.Parse(words[1]); result.AppendFormat("FREQ=MONTHLY;INTERVAL={0}", interval); offset = 3; } else if (string.Equals(words[2], "years")) { // "Every 2 years" int interval = int.Parse(words[1]); result.AppendFormat("FREQ=YEARLY;INTERVAL={0}", interval); offset = 3; } else { throw new ArgumentException(); } } else if (string.Equals(words[0], "after")) { isEvery = false; if (words.Length < 3) throw new ArgumentException(); int interval; if (words[1] == "a" || words[1] == "one") { interval = 1; } else if (words[1] == "two") { interval = 2; } else { interval = int.Parse(words[1]); } Frequency frequency = GetFrequency(words[2]); result.AppendFormat("FREQ={0}", frequency.ToString().ToUpper()); result.AppendFormat(";INTERVAL={0}", interval); offset = 3; } else { throw new ArgumentException("Repeat intervals must start with 'Every' or 'After'."); } if (words.Length > offset) { if (string.Equals(words[offset], "until")) { // "...until 1/2/2007" if (words.Length <= offset + 1) throw new ArgumentException(); StringBuilder dateBuilder = new StringBuilder(); for (int i = offset + 1; i < words.Length; i++) { dateBuilder.Append(words[i]); } FuzzyDateTime date = DateConverter.ParseDateTime(dateBuilder.ToString(), dateFormat); result.AppendFormat(";UNTIL={0}", date.DateTime.ToString("yyyyMMddTHHmmss")); offset = words.Length; } else if (string.Equals(words[offset], "for")) { // "...for 20 times" if (words.Length <= offset + 2) throw new ArgumentException(); if (words[offset + 2] != "times") throw new ArgumentException(); int count = int.Parse(words[offset + 1]); result.AppendFormat(";COUNT={0}", count); offset = offset + 3; } } if (words.Length > offset) throw new ArgumentException(); return new Recurrence(result.ToString(), isEvery); }
private string toFormattedString(DateTimeOffset dateTimeOffset, DateFormat dateFormat) { return(DateTimeToFormattedString.Convert(dateTimeOffset, dateFormat.Short)); }
public static string FormatRecurrence(string repeat, bool isEvery, DateFormat dateFormat) { int count = 0; int interval = 0; string byMonthDay = null; string byDay = null; string until = null; Frequency frequency = Frequency.Daily; string[] repeatParts = repeat.Split(';'); foreach (var part in repeatParts) { string[] partKeyValue = part.Split('='); switch (partKeyValue[0]) { case "FREQ": frequency = (Frequency)Enum.Parse(typeof(Frequency), partKeyValue[1], true); break; case "INTERVAL": interval = int.Parse(partKeyValue[1]); break; case "BYMONTHDAY": byMonthDay = partKeyValue[1]; break; case "BYDAY": byDay = partKeyValue[1]; break; case "UNTIL": until = partKeyValue[1]; break; case "COUNT": count = int.Parse(partKeyValue[1]); break; default: break; } } string s; if (isEvery) { s = "every "; if (!string.IsNullOrEmpty(byMonthDay)) { if (frequency == Frequency.Monthly) { s += "month on the " + GetNumberWithOrdinal(byMonthDay); } } else if (!string.IsNullOrEmpty(byDay)) { if (frequency == Frequency.Monthly) { s += "month on the "; if (byDay.StartsWith("-1")) { s += "last "; byDay = byDay.Substring(2); } else if (byDay.StartsWith("-2")) { s += "2nd last "; byDay = byDay.Substring(2); } else if (byDay.IndexOfAny(new char[] { '1', '2', '3', '4', '5' }) == 0) { s += GetNumberWithOrdinal(byDay.Substring(0, 1)) + " "; byDay = byDay.Substring(1); } } if (interval != 0) { s += GetNumberWithOrdinal(interval) + " "; } if (byDay == "MO,TU,WE,TH,FR") { s += "weekday"; } else if (byDay == "SA,SU") { s += "weekend"; } else { string[] days = byDay.Split(','); for (int i = 0; i < days.Length; i++) { if (i > 0) s += ", "; s += GetDayOfWeek(days[i]).ToString(); } } } else { if (interval > 1) { s += interval + " " + GetFrequencyName(frequency) + "s"; } else { s += GetFrequencyName(frequency); } } if (count > 0) { s += " for " + count.ToString() + " times"; } if (!string.IsNullOrEmpty(until)) { string formattedUntil = until; DateTime untilDateTime; if (DateTime.TryParse(until, out untilDateTime)) { switch (dateFormat) { case DateFormat.European: formattedUntil = untilDateTime.ToString("dd/MM/yy"); break; case DateFormat.American: default: formattedUntil = untilDateTime.ToString("MM/dd/yy"); break; } } s += " until " + formattedUntil; } } else { s = "after " + interval + " " + GetFrequencyName(frequency); if (interval > 1) s += "s"; } return s; }
private void Map(object x, XElement root) { var objType = x.GetType(); var props = objType.GetProperties(); foreach (var prop in props) { var type = prop.PropertyType; if (!type.IsPublic || !prop.CanWrite) { continue; } var name = prop.Name.AsNamespaced(Namespace); var isAttribute = false; //Check for the DeserializeAs attribute on the property var options = prop.GetAttribute <DeserializeAsAttribute>(); if (options != null) { name = options.Name ?? name; isAttribute = options.Attribute; } var value = GetValueFromXml(root, name, isAttribute); if (string.IsNullOrEmpty(value.ToString())) { // special case for inline list items if (type.IsGenericType) { var genericType = type.GetGenericArguments()[0]; var first = GetElementByName(root, genericType.Name); if (first != null) { var elements = root.Elements(first.Name); var list = (IList)Activator.CreateInstance(type); PopulateListFromElements(genericType, elements, list); prop.SetValue(x, list, null); } } continue; } // check for nullable and extract underlying type if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>)) { type = type.GetGenericArguments()[0]; if (string.IsNullOrEmpty(value.ToString())) { continue; } } if (type == typeof(bool)) { var toConvert = value.ToString().ToLower(); prop.SetValue(x, XmlConvert.ToBoolean(toConvert), null); } else if (type.IsPrimitive) { prop.SetValue(x, value.ChangeType(type, Culture), null); } else if (type.IsEnum) { var converted = type.FindEnumValue(value.ToString(), Culture); prop.SetValue(x, converted, null); } else if (type == typeof(Uri)) { var uri = new Uri(value.ToString(), UriKind.RelativeOrAbsolute); prop.SetValue(x, uri, null); } else if (type == typeof(string)) { prop.SetValue(x, value, null); } else if (type == typeof(DateTime)) { if (DateFormat.HasValue()) { value = DateTime.ParseExact(value.ToString(), DateFormat, Culture); } else { value = DateTime.Parse(value.ToString(), Culture); } prop.SetValue(x, value, null); } else if (type == typeof(Decimal)) { value = Decimal.Parse(value.ToString(), Culture); prop.SetValue(x, value, null); } else if (type == typeof(Guid)) { value = new Guid(value.ToString()); prop.SetValue(x, value, null); } else if (type.IsGenericType) { var t = type.GetGenericArguments()[0]; var list = (IList)Activator.CreateInstance(type); var container = GetElementByName(root, name); var first = container.Elements().FirstOrDefault(); var elements = container.Elements().Where(d => d.Name == first.Name); PopulateListFromElements(t, elements, list); prop.SetValue(x, list, null); } else if (type.IsSubclassOfRawGeneric(typeof(List <>))) { // handles classes that derive from List<T> // e.g. a collection that also has properties var list = HandleListDerivative(x, root, name.ToString(), type); prop.SetValue(x, list, null); } else { // nested property classes if (root != null) { var element = GetElementByName(root, name); if (element != null) { var item = CreateAndMap(type, element); prop.SetValue(x, item, null); } } } } }
public static string FormatDateTime(FuzzyDateTime fuzzyDateTime, DateFormat dateFormat, TimeFormat timeFormat) { TimeSpan fromToday = fuzzyDateTime.DateTime.Subtract(DateTime.Today); string timeString = string.Empty; if (fuzzyDateTime.HasTime) { switch (timeFormat) { case TimeFormat.TwelveHours: timeString = fuzzyDateTime.DateTime.ToString("hh:mm tt"); break; case TimeFormat.TwentyFourHours: default: timeString = fuzzyDateTime.DateTime.ToString("HH:mm"); break; } } if (fromToday.Days == 0) { if (fuzzyDateTime.HasTime) { return timeString; } else { return "Today"; } } else if (fromToday.Days == 1) { string result = "Tomorrow"; if (fuzzyDateTime.HasTime) result += " " + timeString; return result; } else if (fromToday.Days == -1) { string result = "Yesterday"; if (fuzzyDateTime.HasTime) result += " " + timeString; return result; } else if (fromToday.Days > 0 && fromToday.Days <= 6) { string result = fuzzyDateTime.DateTime.DayOfWeek.ToString(); if (fuzzyDateTime.HasTime) result += " " + timeString; return result; } else if (fromToday.Days > 6 && fuzzyDateTime.DateTime.Year == DateTime.Today.Year) { string format = "MMM dd"; switch (dateFormat) { case DateFormat.European: format = "dd MMM"; break; case DateFormat.American: default: format = "MMM dd"; break; } string result = fuzzyDateTime.DateTime.ToString(format); if (fuzzyDateTime.HasTime) result += " " + timeString; return result; } else { string format = "MM/dd/yy"; switch (dateFormat) { case DateFormat.European: format = "dd/MM/yy"; break; case DateFormat.American: default: format = "MM/dd/yy"; break; } string result = fuzzyDateTime.DateTime.ToString(format); if (fuzzyDateTime.HasTime) result += " " + timeString; return result; } }
public SelectableDateFormatViewModel(DateFormat dateFormat, bool selected) { DateFormat = dateFormat; Selected = selected; }
/// <summary> /// ��ָ����ʽ���ַ���ת��Ϊ���� /// </summary> public static DateTime ConvertDate(string xDateString, DateFormat xDateFormat, bool isMutiLang) { if (string.IsNullOrEmpty(xDateString)) return DateTime.MinValue; Regex r; switch (xDateFormat) { case DateFormat.ddMMyyyys: #region ddMMyyyys Convert string[] dateInfo = xDateString.Split('/'); string dd = string.Empty; string MM = string.Empty; string yyyy = string.Empty; if (dateInfo.Length == 3) { dd = dateInfo[0].Trim(); if (dd.Length != 2) { if (dd.Length > 2) { dd = dd.Substring(0, 2); } else if (dd.Length == 1 && dd != "0") { dd = "0" + dd; } else { dd = "01"; } } else if (dd == "00") { dd = "01"; } MM = dateInfo[1].Trim(); if (MM.Length != 2) { if (MM.Length > 2) { MM = MM.Substring(0, 2); } else if (MM.Length == 1) { MM = "0" + MM; } else { MM = "01"; } } else if (MM == "00") { MM = "01"; } yyyy = dateInfo[2].Trim(); if (yyyy.Length == 2) { if (NumberHelper.ToInt(yyyy, 0) < 70) yyyy = "20" + yyyy; else yyyy = "19" + yyyy; } else if (yyyy.Length != 4) { if (yyyy.Length > 4) { yyyy = yyyy.Substring(0, 4); } else { yyyy = DateTime.Now.ToString("yyyy"); } } else if (yyyy == "0000") { yyyy = DateTime.Now.ToString("yyyy"); } } else { return DateTime.MinValue; } xDateString = string.Format("{0}/{1}/{2}", dd, MM, yyyy); #endregion break; case DateFormat.yyyyMMddd: r = new Regex("[0-9]{4}-[0-9]{2}-[0-9]{2}"); if (!r.IsMatch(xDateString)) { r = new Regex(@"(?<year>(?: *[0-9]{2}|[0-9]{4}) *)(?<split>[- /])(?<month> *[0-9]{1,2} *)\2(?<day> *[0-9]{1,2} *)"); if (!r.IsMatch(xDateString)) { return DateTime.MinValue; } else { GroupCollection gs = r.Match(xDateString).Groups; xDateString = ParseDate(gs["year"].Value, gs["month"].Value, gs["day"].Value, "", "", "").ToString("yyyy-MM-dd"); } } break; case DateFormat.yyyyMMdddHHmmss: r = new Regex("[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}"); if (!r.IsMatch(xDateString)) { r = new Regex(@"(?<year>(?: *[0-9]{2}|[0-9]{4}) *)(?<split>[- /])(?<month> *[0-9]{1,2} *)\2(?<day> *[0-9]{1,2} *) (?<hour> *[0-9]{1,2} *):(?<minute> *[0-9]{1,2} *):(?<second> *[0-9]{1,2} *)"); if (!r.IsMatch(xDateString)) { return DateTime.MinValue; } else { GroupCollection gs = r.Match(xDateString).Groups; xDateString = ParseDate(gs["year"].Value, gs["month"].Value, gs["day"].Value, gs["hour"].Value, gs["minute"].Value, gs["second"].Value).ToString("yyyy-MM-dd"); } } break; case DateFormat.ddMMyyyyn: break; case DateFormat.ddMMyyyysp: break; case DateFormat.ddMMyyyyd: break; case DateFormat.ddMMMyyyys: break; case DateFormat.ddMMMyyyyn: break; case DateFormat.ddMMMyyyysp: break; case DateFormat.ddMMMyyyyd: break; case DateFormat.MMMddyyyyspcm: break; case DateFormat.ddMMMyyyyspwt: break; case DateFormat.ddMMMyyyyHHmm: break; case DateFormat.yyyyMMMdd: break; case DateFormat.yyyyMMdd: break; case DateFormat.yyMMddHHmm: break; case DateFormat.MMMdd: break; case DateFormat.ddMMMyyyyddd: break; case DateFormat.ddMMMyyyyml: break; default: break; } return ConvertDate(xDateString, xDateFormat.ToString(), isMutiLang); }
public static void RenderLocalizedDate(Interpreter interpreter, IFormatting?element, IVariable?value, string?delimiter, DateFormat dateFormat, DatePrecision precision, IEnumerable <DatePartElement> dateParts) { var parts = new List <DatePartElement>(); var locale = interpreter.LocaleFile; var localeDate = locale.Dates !.FirstOrDefault(e => e.Format == dateFormat); parts.AddRange(localeDate.DateParts); if (dateParts != null) { foreach (var part in dateParts) { Replace(parts, part.Name, part); } } RenderDate(interpreter, element, value, delimiter, precision, parts.ToArray()); }
/// <summary> /// ȡ�����ڸ�ʽ��ʵ�ʸ�ʽ�ַ��� /// </summary> /// <param name="xDateFormat"></param> /// <returns></returns> internal static string GetDateString(DateFormat xDateFormat) { return Resources.Date.ResourceManager.GetString(xDateFormat.ToString()); }
internal void SetDateFormat(DateFormat dateFormat) { DateFormatID = dateFormat.ID.ToString(); }
public static DateTime ConvertDate(string xDateString, DateFormat xDateFormat, bool isMutiLang) { if (string.IsNullOrEmpty(xDateString)) return DateTime.MinValue; switch (xDateFormat) { case DateFormat.ddMMyyyys: string[] dateInfo = xDateString.Split('/'); string dd = string.Empty; string MM = string.Empty; string yyyy = string.Empty; if (dateInfo.Length == 3) { dd = dateInfo[0].Trim(); if (dd.Length != 2) { if (dd.Length > 2) { dd = dd.Substring(0, 2); } else if (dd.Length == 1 && dd != "0") { dd = "0" + dd; } else { dd = "01"; } } else if (dd == "00") { dd = "01"; } MM = dateInfo[1].Trim(); if (MM.Length != 2) { if (MM.Length > 2) { MM = MM.Substring(0, 2); } else if (MM.Length == 1) { MM = "0" + MM; } else { MM = "01"; } } else if (MM == "00") { MM = "01"; } yyyy = dateInfo[2].Trim(); if (yyyy.Length == 2) { yyyy += "20"; } else if (yyyy.Length != 4) { if (yyyy.Length > 4) { yyyy = yyyy.Substring(0, 4); } else { yyyy = DateTime.Now.ToString("yyyy"); } } else if (yyyy == "0000") { yyyy = DateTime.Now.ToString("yyyy"); } } else { return DateTime.MinValue; } xDateString = string.Format("{0}/{1}/{2}", dd, MM, yyyy); break; case DateFormat.ddMMyyyyn: break; case DateFormat.ddMMyyyysp: break; case DateFormat.ddMMyyyyd: break; case DateFormat.ddMMMyyyys: break; case DateFormat.ddMMMyyyyn: break; case DateFormat.ddMMMyyyysp: break; case DateFormat.ddMMMyyyyd: break; case DateFormat.MMMddyyyyspcm: break; case DateFormat.ddMMMyyyyspwt: break; case DateFormat.ddMMMyyyyHHmm: break; case DateFormat.yyyyMMMdd: break; case DateFormat.yyyyMMdd: break; case DateFormat.yyMMddHHmm: break; case DateFormat.MMMdd: break; case DateFormat.ddMMMyyyyddd: break; case DateFormat.ddMMMyyyyml: break; default: break; } MutiLanguage.Languages lang = MutiLanguage.GetCultureType(); lang = isMutiLang ? lang : MutiLanguage.Languages.en_us; string langstr = isMutiLang ? MutiLanguage.EnumToString(lang) : MutiLanguage.EnumToString(MutiLanguage.Languages.en_us); System.Resources.ResourceManager rm = new System.Resources.ResourceManager(typeof(Resources.Date)); System.Resources.ResourceSet rs = rm.GetResourceSet(new System.Globalization.CultureInfo(langstr), true, true); return DateTime.ParseExact(xDateString, rs.GetString(xDateFormat.ToString()), System.Globalization.DateTimeFormatInfo.InvariantInfo); }
public void Test5345parse() { // Test parse with incomplete information DateFormat fmt2 = IBM.ICU.Text.DateFormat.GetDateInstance(); // DateFormat.LONG, // Locale.US); IBM.ICU.Util.JapaneseCalendar c = new IBM.ICU.Util.JapaneseCalendar(IBM.ICU.Util.TimeZone.GetDefault(), new ULocale("en_US")); SimpleDateFormat fmt = (SimpleDateFormat)c.GetDateTimeFormat(1, 1, new ULocale("en_US@calendar=japanese")); fmt.ApplyPattern("G y"); Logln("fmt's locale = " + fmt.GetLocale(IBM.ICU.Util.ULocale.ACTUAL_LOCALE)); // SimpleDateFormat fmt = new SimpleDateFormat("G y", new // Locale("en_US@calendar=japanese")); long aDateLong = -3197120400000L + 3600000L; // compensate for DST DateTime aDate = ILOG.J2CsMapping.Util.DateUtil.DateFromJavaMillis(aDateLong); // 08 Sept 1868 Logln("aDate: " + aDate.ToString() + ", from " + aDateLong); String str; str = fmt2.Format(aDate); Logln("Test Date: " + str); str = fmt.Format(aDate); Logln("as Japanese Calendar: " + str); String expected = "Meiji 1"; if (!str.Equals(expected)) { Errln("FAIL: Expected " + expected + " but got " + str); } DateTime otherDate; try { otherDate = fmt.Parse(expected); if (!otherDate.Equals(aDate)) { String str3; // ParsePosition pp; DateTime dd = fmt.Parse(expected); str3 = fmt.Format(otherDate); long oLong = ILOG.J2CsMapping.Util.DateUtil.DotNetDateToJavaMillis(otherDate); long aLong = ILOG.J2CsMapping.Util.DateUtil.DotNetDateToJavaMillis(aDate); Errln("FAIL: Parse incorrect of " + expected + ": wanted " + aDate + " (" + aLong + "), but got " + " " + otherDate + " (" + oLong + ") = " + str3 + " not " + dd.ToString()); } else { Logln("Parsed OK: " + expected); } } catch (ILOG.J2CsMapping.Util.ParseException pe) { Errln("FAIL: ParseException: " + pe.ToString()); Console.Error.WriteLine(pe.StackTrace); } }
public static DateTime ConvertDate(string xDateString, DateFormat xDateFormat, string xTimeString) { DateTime xDate = ConvertDate(xDateString, xDateFormat); TimeSpan xTime = ConvertTime(xTimeString); return new DateTime(xDate.Year, xDate.Month, xDate.Day, xTime.Hours, xTime.Minutes, xTime.Seconds); }
public void TestCoverage() { { // new JapaneseCalendar(TimeZone) IBM.ICU.Util.JapaneseCalendar cal = new IBM.ICU.Util.JapaneseCalendar(IBM.ICU.Util.TimeZone.GetDefault()); if (cal == null) { Errln("could not create JapaneseCalendar with TimeZone"); } } { // new JapaneseCalendar(ULocale) IBM.ICU.Util.JapaneseCalendar cal_0 = new IBM.ICU.Util.JapaneseCalendar(IBM.ICU.Util.ULocale.GetDefault()); if (cal_0 == null) { Errln("could not create JapaneseCalendar with ULocale"); } } { // new JapaneseCalendar(TimeZone, ULocale) IBM.ICU.Util.JapaneseCalendar cal_1 = new IBM.ICU.Util.JapaneseCalendar(IBM.ICU.Util.TimeZone.GetDefault(), IBM.ICU.Util.ULocale.GetDefault()); if (cal_1 == null) { Errln("could not create JapaneseCalendar with TimeZone ULocale"); } } { // new JapaneseCalendar(Locale) IBM.ICU.Util.JapaneseCalendar cal_2 = new IBM.ICU.Util.JapaneseCalendar(ILOG.J2CsMapping.Util.Locale.GetDefault()); if (cal_2 == null) { Errln("could not create JapaneseCalendar with Locale"); } } { // new JapaneseCalendar(TimeZone, Locale) IBM.ICU.Util.JapaneseCalendar cal_3 = new IBM.ICU.Util.JapaneseCalendar(IBM.ICU.Util.TimeZone.GetDefault(), ILOG.J2CsMapping.Util.Locale.GetDefault()); if (cal_3 == null) { Errln("could not create JapaneseCalendar with TimeZone Locale"); } } { // new JapaneseCalendar(Date) IBM.ICU.Util.JapaneseCalendar cal_4 = new IBM.ICU.Util.JapaneseCalendar(DateTime.Now); if (cal_4 == null) { Errln("could not create JapaneseCalendar with Date"); } } { // new JapaneseCalendar(int year, int month, int date) IBM.ICU.Util.JapaneseCalendar cal_5 = new IBM.ICU.Util.JapaneseCalendar(1868, IBM.ICU.Util.Calendar.JANUARY, 1); if (cal_5 == null) { Errln("could not create JapaneseCalendar with year,month,date"); } } { // new JapaneseCalendar(int era, int year, int month, int date) IBM.ICU.Util.JapaneseCalendar cal_6 = new IBM.ICU.Util.JapaneseCalendar(IBM.ICU.Util.JapaneseCalendar.MEIJI, 43, IBM.ICU.Util.Calendar.JANUARY, 1); if (cal_6 == null) { Errln("could not create JapaneseCalendar with era,year,month,date"); } } { // new JapaneseCalendar(int year, int month, int date, int hour, int // minute, int second) IBM.ICU.Util.JapaneseCalendar cal_7 = new IBM.ICU.Util.JapaneseCalendar(1868, IBM.ICU.Util.Calendar.JANUARY, 1, 1, 1, 1); if (cal_7 == null) { Errln("could not create JapaneseCalendar with year,month,date,hour,min,second"); } } { // limits IBM.ICU.Util.JapaneseCalendar cal_8 = new IBM.ICU.Util.JapaneseCalendar(); DateFormat fmt = cal_8.GetDateTimeFormat(IBM.ICU.Text.DateFormat.FULL, IBM.ICU.Text.DateFormat.FULL, new ILOG.J2CsMapping.Util.Locale("en")); cal_8.Set(IBM.ICU.Util.Calendar.ERA, IBM.ICU.Util.JapaneseCalendar.MEIJI); Logln("date: " + cal_8.GetTime()); Logln("min era: " + cal_8.GetMinimum(IBM.ICU.Util.Calendar.ERA)); Logln("min year: " + cal_8.GetMinimum(IBM.ICU.Util.Calendar.YEAR)); cal_8.Set(IBM.ICU.Util.Calendar.YEAR, cal_8.GetActualMaximum(IBM.ICU.Util.Calendar.YEAR)); Logln("date: " + fmt.Format(cal_8.GetTime())); cal_8.Add(IBM.ICU.Util.Calendar.YEAR, 1); Logln("date: " + fmt.Format(cal_8.GetTime())); } { // data IBM.ICU.Util.JapaneseCalendar cal_9 = new IBM.ICU.Util.JapaneseCalendar(1868, IBM.ICU.Util.Calendar.JANUARY, 1); DateTime time = cal_9.GetTime(); String[] calendarLocales = { "en", "ja_JP" }; String[] formatLocales = { "en", "ja" }; for (int i = 0; i < calendarLocales.Length; ++i) { String calLocName = calendarLocales[i]; ILOG.J2CsMapping.Util.Locale calLocale = IBM.ICU.Impl.LocaleUtility.GetLocaleFromName(calLocName); cal_9 = new IBM.ICU.Util.JapaneseCalendar(calLocale); for (int j = 0; j < formatLocales.Length; ++j) { String locName = formatLocales[j]; ILOG.J2CsMapping.Util.Locale formatLocale = IBM.ICU.Impl.LocaleUtility .GetLocaleFromName(locName); DateFormat format = IBM.ICU.Text.DateFormat.GetDateTimeInstance(cal_9, IBM.ICU.Text.DateFormat.FULL, IBM.ICU.Text.DateFormat.FULL, formatLocale); Logln(calLocName + "/" + locName + " --> " + format.Format(time)); } } } }
public static string FormatDateTimeToString(DateTime xDateTime, DateFormat xDateFormat) { return FormatDateTimeToString(xDateTime, xDateFormat, false); }
private void Map(object x, JToken json) { var objType = x.GetType(); var props = objType.GetProperties().Where(p => p.CanWrite).ToList(); foreach (var prop in props) { var type = prop.PropertyType; var name = prop.Name; var actualName = name.GetNameVariants(Culture).FirstOrDefault(n => json[n] != null); var value = actualName != null ? json[actualName] : null; if (value == null || value.Type == JTokenType.Null) { continue; } // check for nullable and extract underlying type if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>)) { type = type.GetGenericArguments()[0]; } if (type.IsPrimitive) { // no primitives can contain quotes so we can safely remove them // allows converting a json value like {"index": "1"} to an int var tmpVal = value.AsString().Replace("\"", string.Empty); prop.SetValue(x, tmpVal.ChangeType(type), null); } else if (type.IsEnum) { var converted = type.FindEnumValue(value.AsString(), Culture); prop.SetValue(x, converted, null); } else if (type == typeof(Uri)) { string raw = value.AsString(); var uri = new Uri(raw, UriKind.RelativeOrAbsolute); prop.SetValue(x, uri, null); } else if (type == typeof(string)) { string raw = value.AsString(); prop.SetValue(x, raw, null); } else if (type == typeof(DateTime) || type == typeof(DateTimeOffset)) { DateTime dt; if (DateFormat.HasValue()) { var clean = value.AsString(); dt = DateTime.ParseExact(clean, DateFormat, Culture); } else if (value.Type == JTokenType.Date) { dt = value.Value <DateTime>().ToUniversalTime(); } else { // try parsing instead dt = value.AsString().ParseJsonDate(Culture); } if (type == typeof(DateTime)) { prop.SetValue(x, dt, null); } else if (type == typeof(DateTimeOffset)) { prop.SetValue(x, (DateTimeOffset)dt, null); } } else if (type == typeof(Decimal)) { var dec = Decimal.Parse(value.AsString(), Culture); prop.SetValue(x, dec, null); } else if (type == typeof(Guid)) { string raw = value.AsString(); var guid = string.IsNullOrEmpty(raw) ? Guid.Empty : new Guid(raw); prop.SetValue(x, guid, null); } else if (type.IsGenericType) { var genericTypeDef = type.GetGenericTypeDefinition(); if (genericTypeDef == typeof(List <>)) { var list = BuildList(type, value.Children()); prop.SetValue(x, list, null); } else if (genericTypeDef == typeof(Dictionary <,>)) { var keyType = type.GetGenericArguments()[0]; // only supports Dict<string, T>() if (keyType == typeof(string)) { var dict = BuildDictionary(type, value.Children()); prop.SetValue(x, dict, null); } } else { // nested property classes var item = CreateAndMap(type, json[actualName]); prop.SetValue(x, item, null); } } else { // nested property classes var item = CreateAndMap(type, json[actualName]); prop.SetValue(x, item, null); } } }
public static string FormatDateToString(object xDateTime, DateFormat xDateFormat, bool isMutiLang) { return FormatDateTimeToString(Convert.ToDateTime(xDateTime), xDateFormat, isMutiLang); }
// Logging to file facilities. // The prefix is used to append stuff in front of the logging messages /// <exception cref="System.IO.IOException"/> public virtual void InitLog(File logFilePath) { RedwoodConfiguration.Empty().Handlers(RedwoodConfiguration.Handlers.Chain(RedwoodConfiguration.Handlers.ShowAllChannels(), RedwoodConfiguration.Handlers.stderr), RedwoodConfiguration.Handlers.File(logFilePath.ToString())).Apply(); // fh.setFormatter(new NewlineLogFormatter()); System.Console.Out.WriteLine("Starting Ssurgeon log, at " + logFilePath.GetAbsolutePath() + " date=" + DateFormat.GetDateInstance(DateFormat.Full).Format(new DateTime())); log.Info("Starting Ssurgeon log, date=" + DateFormat.GetDateInstance(DateFormat.Full).Format(new DateTime())); }
public static string GetDateString(DateFormat xDateFormat) { string myDateString = string.Empty; switch (xDateFormat) { case DateFormat.ddMMyyyys: myDateString = Resources.Date.ddMMyyyys; break; case DateFormat.ddMMyyyyn: myDateString = Resources.Date.ddMMyyyyn; break; case DateFormat.ddMMyyyysp: myDateString = Resources.Date.ddMMyyyysp; break; case DateFormat.ddMMyyyyd: myDateString = Resources.Date.ddMMyyyyd; break; case DateFormat.ddMMMyyyys: myDateString = Resources.Date.ddMMMyyyys; break; case DateFormat.ddMMMyyyyn: myDateString = Resources.Date.ddMMMyyyyn; break; case DateFormat.ddMMMyyyysp: myDateString = Resources.Date.ddMMMyyyysp; break; case DateFormat.ddMMMyyyyd: myDateString = Resources.Date.ddMMMyyyyd; break; case DateFormat.MMMddyyyyspcm: myDateString = Resources.Date.MMMddyyyyspcm; break; case DateFormat.ddMMMyyyyspwt: myDateString = Resources.Date.ddMMMyyyyspwt; break; case DateFormat.ddMMMyyyyHHmm: myDateString = Resources.Date.ddMMMyyyyHHmm; break; case DateFormat.yyyyMMMdd: myDateString = Resources.Date.yyyyMMMdd; break; case DateFormat.yyyyMMdd: myDateString = Resources.Date.yyyyMMdd; break; case DateFormat.yyyyMMddd: myDateString = Resources.Date.yyyyMMddd; break; case DateFormat.yyMMddHHmm: myDateString = Resources.Date.yyMMddHHmm; break; case DateFormat.MMMdd: myDateString = Resources.Date.MMMdd; break; case DateFormat.ddMMMyyyyddd: myDateString = Resources.Date.ddMMMyyyyddd; break; case DateFormat.ddMMMyyyyml: myDateString = Resources.Date.ddMMMyyyyml.ToString(); break; case DateFormat.ddMMMml: myDateString = Resources.Date.ddMMMml.ToString(); break; case DateFormat.ddMMMspwt: myDateString = Resources.Date.ddMMMspwt; break; case DateFormat.yyMMddHHmms: myDateString = Resources.Date.ddMMMspwt; break; //case DateFormat.MMMddyyyyq: // myDateString = "MMM dd'yyyy"; // break; case DateFormat.ddMMMyyyy: myDateString = Resources.Date.ddMMMyyyy; break; case DateFormat.MMMyyyy: myDateString = Resources.Date.MMMyyyy; break; case DateFormat.dd_space_MMM_comma_yyyy: myDateString = Resources.Date.dd_space_MMM_comma_yyyy; break; default: myDateString = Resources.Date.GetResource(xDateFormat.ToString()); break; } return myDateString; }
private object ConvertValue(Type type, object value) { var stringValue = Convert.ToString(value, Culture); if (type.IsPrimitive) { // no primitives can contain quotes so we can safely remove them // allows converting a json value like {"index": "1"} to an int var tmpVal = stringValue.Replace("\"", string.Empty); return(tmpVal.ChangeType(type, Culture)); } else if (type.IsEnum) { return(type.FindEnumValue(stringValue, Culture)); } else if (type == typeof(Uri)) { return(new Uri(stringValue, UriKind.RelativeOrAbsolute)); } else if (type == typeof(string)) { return(stringValue); } else if (type == typeof(DateTime) #if !PocketPC || type == typeof(DateTimeOffset) #endif ) { DateTime dt; if (DateFormat.HasValue()) { dt = DateTime.ParseExact(stringValue, DateFormat, Culture); } else { // try parsing instead dt = stringValue.ParseJsonDate(Culture); } if (type == typeof(DateTime)) { return(dt); } #if !PocketPC else if (type == typeof(DateTimeOffset)) { return((DateTimeOffset)dt); } #endif } else if (type == typeof(Decimal)) { return(Decimal.Parse(stringValue, Culture)); } else if (type == typeof(Guid)) { return(string.IsNullOrEmpty(stringValue) ? Guid.Empty : new Guid(stringValue)); } else if (type == typeof(TimeSpan)) { return(TimeSpan.Parse(stringValue)); } else if (type.IsGenericType) { var genericTypeDef = type.GetGenericTypeDefinition(); if (genericTypeDef == typeof(List <>)) { return(BuildList(type, value)); } else if (genericTypeDef == typeof(Dictionary <,>)) { var keyType = type.GetGenericArguments()[0]; // only supports Dict<string, T>() if (keyType == typeof(string)) { return(BuildDictionary(type, value)); } } else { // nested property classes return(CreateAndMap(type, value)); } } else { // nested property classes return(CreateAndMap(type, value)); } return(null); }
public override void SetDate(DateTime? dateTime, DateFormat dateFormat) { var valuePattern = (ValuePattern)AutomationElement.GetCurrentPattern(ValuePattern.Pattern); valuePattern.SetValue(dateTime != null ? dateTime.Value.ToShortDateString() : null); }
private IEnumerable <UILabel> createHorizontalLegendLabels(IEnumerable <DateTimeOffset> dates, DateFormat format) => dates.Select(date => new BarLegendLabel( DateTimeOffsetConversion.ToDayOfWeekInitial(date), date.ToString(format.Short, CultureInfo.InvariantCulture)));