public void TestPerformance() { CountDownLatch simpleDateFormatGate = new CountDownLatch(CONCURRENCY); CountDownLatch simpleDateFormatFinisher = new CountDownLatch(CONCURRENCY); AtomicLong simpleDateFormatCount = new AtomicLong(); for(int i = 0; i < CONCURRENCY; i++) { new ThRead(new SimpleDateFormatTask(simpleDateFormatFinisher, simpleDateFormatGate, simpleDateFormatCount, FORMAT)).start(); } simpleDateFormatFinisher.await(); CountDownLatch synchronizedGate = new CountDownLatch(CONCURRENCY); CountDownLatch synchronizedFinisher = new CountDownLatch(CONCURRENCY); AtomicLong synchronizedCount = new AtomicLong(); SimpleDateFormat format = new SimpleDateFormat(FORMAT); for(int i = 0; i < CONCURRENCY; i++) { new ThRead(new SynchronizedTask(synchronizedFinisher, synchronizedGate, synchronizedCount, format)).start(); } synchronizedFinisher.await(); CountDownLatch formatterGate = new CountDownLatch(CONCURRENCY); CountDownLatch formatterFinisher = new CountDownLatch(CONCURRENCY); AtomicLong formatterCount = new AtomicLong(); DateFormatter formatter = new DateFormatter(FORMAT, CONCURRENCY); for(int i = 0; i < CONCURRENCY; i++) { new ThRead(new FormatterTask(formatterFinisher, formatterGate, formatterCount, formatter)).start(); } formatterFinisher.await(); System.err.printf("pool: %s, new: %s, synchronized: %s", formatterCount.get(), simpleDateFormatCount.get(), synchronizedCount.get()); //assertTrue(formatterCount.get() < simpleDateFormatCount.get()); //assertTrue(formatterCount.get() < synchronizedCount.get()); // Synchronized is faster? }
public RemoteViews GetViewAt (int position) { IList<RichPushMessage> messages = RichPushManager.Shared ().RichPushUser.Inbox.Messages; if (position > messages.Count) { return null; } // Get the data for this position from the content provider RichPushMessage message = messages [position]; // Return a proper item String formatStr = context.Resources.GetString (Resource.String.item_format_string); int itemId = Resource.Layout.widget_item; RemoteViews rv = new RemoteViews (context.PackageName, itemId); rv.SetTextViewText (Resource.Id.widget_item_text, Java.Lang.String.Format (formatStr, message.Title)); int iconDrawable = message.IsRead ? Resource.Drawable.mark_read : Resource.Drawable.mark_unread; rv.SetImageViewResource (Resource.Id.widget_item_icon, iconDrawable); SimpleDateFormat dateFormat = new SimpleDateFormat ("yyyy-MM-dd HH:mm"); rv.SetTextViewText (Resource.Id.date_sent, dateFormat.Format (message.SentDate)); // Add the message id to the intent Intent fillInIntent = new Intent (); Bundle extras = new Bundle (); extras.PutString (RichPushApplication.MESSAGE_ID_RECEIVED_KEY, message.MessageId); fillInIntent.PutExtras (extras); rv.SetOnClickFillInIntent (Resource.Id.widget_item, fillInIntent); return rv; }
public void OnTimeChanged (TimePicker view, int hourOfDay, int minute) { var calendar = Calendar.Instance; calendar.Set(CalendarField.HourOfDay,timePicker.CurrentHour.IntValue()); calendar.Set (CalendarField.Minute, timePicker.CurrentMinute.IntValue()); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); dateTime = sdf.Format (calendar.Time); }
public void OnDateChanged (DatePicker view, int year, int monthOfYear, int dayOfMonth) { var calendar = Calendar.Instance; calendar.Set (datePicker.Year, datePicker.Month, datePicker.DayOfMonth); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); dateTime = sdf.Format (calendar.Time); }
public static DateTime ToDateTime(string s, string[] formats) { foreach (var format in formats) { var simpleDateFormat = new SimpleDateFormat(ToJavaFormat(format), Locale.US); var parsePosition = new ParsePosition(0); var date = simpleDateFormat.Parse(s, parsePosition); if (date != null && parsePosition.Index != 0) return DateTime.FromDate(date); } throw new ArgumentException(s + " cannot be parsed as DateTime"); }
public static string GetMonthDate(Date date, Locale locale, Context context) { if (Build.VERSION.SdkInt >= Build.VERSION_CODES.JellyBeanMr2) { var pattern = Android.Text.Format.DateFormat.GetBestDateTimePattern(locale, FORMAT_MMDD); var sdf = new SimpleDateFormat(pattern, locale); return sdf.Format(date); } else { var flag = FormatStyleFlags.ShowDate | FormatStyleFlags.NoYear; return DateUtils.FormatDateTime(context, date.Time, flag); } }
protected async void SendLocationDataToWebsite ( Location location ) { var dateFormat = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss"); var date = new Date (location.Time); var prefs = this.GetSharedPreferences ("lok", 0); var editor = prefs.Edit (); var totalDistance = prefs.GetFloat ("totalDistance", 0f); var firstTimePosition = prefs.GetBoolean ("firstTimePosition", true); var distance = 0; if (firstTimePosition) editor.PutBoolean ("firstTimePosition", false); else { var prevLocation = new Location ("") { Latitude = prefs.GetFloat ("prevLat", 0f), Longitude = prefs.GetFloat ("prevLong", 0f) }; distance = (int) location.DistanceTo (prevLocation); totalDistance += distance; editor.PutFloat ("totalDistance", totalDistance); } editor.PutFloat ("prevLat", (float) location.Latitude); editor.PutFloat ("prevLong", (float) location.Longitude); editor.Apply (); // TODO : add parameters for post requests. // Hint : using HttpClient(); using (var client = new HttpClient ()) { var values = new Dictionary<string, string> () { { "latitude", location.Latitude.ToString() }, { "longitude", location.Longitude.ToString() }, { "speed", location.Speed.ToString() }, { "date", System.Uri.EscapeDataString(DateTime.Now.ToString()) }, { "locationmethod", location.Provider }, { "distance", distance.ToString() }, { "username", prefs.GetString("username", "") }, { "sessionid", prefs.GetString("sessionId", "") }, { "accuracy", location.Accuracy.ToString() } }; var content = new FormUrlEncodedContent (values); await client.PostAsync (_defaultUploadWebsite, content); } }
public override void Start() { base.Start(); var result = _systemCache.WeatherDetails; Country = result.Sys.Country; CityName = "Weather in " + result.Name + ", " + Country; Icon = result.Weather[0].Icon; IconUrl = _url + Icon + ".png"; Temperature = result.Main.Temperature + " \u2103"; Date dt = new Date(Convert.ToInt64(result.Lastupdate) * 1000); SimpleDateFormat sfd = new SimpleDateFormat("yyyy/MM/dd HH:mm"); Date_Time = sfd.Format(dt).ToString(); Description = result.Weather[0].Description + "\n" + "Updated at " + Date_Time; Wind = result.Wind.Speed; Cloudiness = result.Clouds.All; Pressure = result.Main.Pressure; Humidity = result.Main.Humidity; Date dtSunrise = new Date(Convert.ToInt64(result.Sys.Sunrise) * 1000); SimpleDateFormat sfdSunrise = new SimpleDateFormat("HH:mm"); Sunrise = sfdSunrise.Format(dtSunrise).ToString(); Date dtSunset = new Date(Convert.ToInt64(result.Sys.Sunset) * 1000); SimpleDateFormat sfdSunset = new SimpleDateFormat("HH:mm"); Sunset = sfdSunset.Format(dtSunset).ToString(); Coords = "[" + result.Coordinate.Latitude + ", " + result.Coordinate.Longitude + "]"; MyListItems.Add(new WeatherDetail("Wind", Wind + " km/h")); MyListItems.Add(new WeatherDetail("Cloudiness", Cloudiness + " %")); MyListItems.Add(new WeatherDetail("Pressure", Pressure + " hpa")); MyListItems.Add(new WeatherDetail("Humidity", Humidity + " %")); MyListItems.Add(new WeatherDetail("Sunrise", Sunrise)); MyListItems.Add(new WeatherDetail("Sunset", Sunset)); MyListItems.Add(new WeatherDetail("Coords", Coords)); }
private void UpdateProgressControls() { int currentPos = mediaPlayer.CurrentPosition; int duration = mediaPlayer.Duration; CurrentSongPosition = currentPos; try { SimpleDateFormat dateFormat = new SimpleDateFormat("mm:ss"); lblPosNow.Text = dateFormat.Format(new Date(currentPos)); lblPosEnd.Text = dateFormat.Format(new Date(duration)); } catch (Exception ex) { } //lblPosNow.Text = new DateTime(currentPos).ToString("mm:ss"); //lblPosEnd.Text = new DateTime(duration).ToString("mm:ss"); }
public virtual void decisionInputInstanceValue() { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS"); DateTime fixedDate = sdf.parse("01/01/2001 01:01:01.000"); ClockUtil.CurrentTime = fixedDate; startProcessInstanceAndEvaluateDecision(inputValue); HistoricDecisionInstance historicDecisionInstance = engineRule.HistoryService.createHistoricDecisionInstanceQuery().includeInputs().singleResult(); IList <HistoricDecisionInputInstance> inputInstances = historicDecisionInstance.Inputs; assertThat(inputInstances.Count, @is(1)); HistoricDecisionInputInstance inputInstance = inputInstances[0]; assertThat(inputInstance.TypeName, @is(valueType)); assertThat(inputInstance.Value, @is(inputValue)); assertThat(inputInstance.CreateTime, @is(fixedDate)); }
/// <summary> /// To display the week day title /// </summary> /// <returns>SUN, MON, TUE, WED, THU, FRI, SAT</returns> protected List <string> DaysOfWeekTitles() { var daysOfWeek = new List <string>(); var formatter = new SimpleDateFormat("EEE", Locale.Default); var weekdaySunday = (int)System.DayOfWeek.Sunday; var daySunday = new DateTime(2000, 10, 1); var day = daySunday.AddDays(_startDayOfWeek - weekdaySunday); for (var i = 0; i < 7; i++) { var date = CalendarHelper.ConvertDateTimeToDate(day); var dayFormatted = formatter.Format(date).ToLower(); daysOfWeek.Add(dayFormatted); day = day.AddDays(1); } return(daysOfWeek); }
public void SetVersionNumber() { var lstPackages = PackageManager.GetInstalledPackages(0); string Info = string.Empty; ApplicationInfo ai = PackageManager.GetApplicationInfo(PackageName, 0); ZipFile zf = new ZipFile(ai.SourceDir); ZipEntry ze = zf.GetEntry("META-INF/MANIFEST.MF"); long time = ze.Time; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); string date = sdf.Format(new Java.Util.Date(ze.Time)); zf.Close(); tvVersionNumber.Text = "版本:" + DataBase.VersionNumber + date; //TODO:现在暂时没有使用 // tvEquipmentNumber.Text = "设备号:" + DataBase.EquipmentNumber; }
private static DateFormatResult CreateFormat(string format, IFormatProvider provider) { if (format == null || format.Length == 1) { var ret = GetStandardFormat(format == null ? 'G' : format[0], provider); if (ret != null) { return(ret); } } bool useInvariant, foundK, useUtc; string javaFormat = DateTimeFormatting.ToJavaFormatString(format, provider, DateTimeKind.Unspecified, false, out useInvariant, out foundK, out useUtc); Java.Util.Locale locale = useInvariant ? CultureInfo.InvariantCulture.Locale : provider.ToLocale(); DateFormat formatter = new SimpleDateFormat(javaFormat, locale); return(new DateFormatResult(formatter, foundK, useUtc)); }
public static string BuildThreadDiagnosticString() { StringWriter sw = new StringWriter(); PrintWriter output = new PrintWriter(sw); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss,SSS"); output.WriteLine(string.Format("Timestamp: %s", dateFormat.Format(new DateTime()) )); output.WriteLine(); output.WriteLine(BuildThreadDump()); string deadlocksInfo = BuildDeadlockInfo(); if (deadlocksInfo != null) { output.WriteLine("====> DEADLOCKS DETECTED <===="); output.WriteLine(); output.WriteLine(deadlocksInfo); } return(sw.ToString()); }
public void TestJapaneseYear3282() { IBM.ICU.Util.Calendar c = IBM.ICU.Util.Calendar.GetInstance(IBM.ICU.Util.ULocale.ENGLISH); c.Set(2003, IBM.ICU.Util.Calendar.SEPTEMBER, 25); IBM.ICU.Util.JapaneseCalendar jcal = new IBM.ICU.Util.JapaneseCalendar(); // jcal.setTime(new Date(1187906308151L)); alternate value jcal.SetTime(c.GetTime()); Logln("Now is: " + jcal.GetTime()); c.SetTime(jcal.GetTime()); int nowYear = c.Get(IBM.ICU.Util.Calendar.YEAR); Logln("Now year: " + nowYear); SimpleDateFormat jdf = (SimpleDateFormat)IBM.ICU.Text.DateFormat .GetDateInstance(jcal, IBM.ICU.Text.DateFormat.DEFAULT, ILOG.J2CsMapping.Util.Locale.GetDefault()); jdf.ApplyPattern("G yy/MM/dd"); String text = jdf.Format(jcal.GetTime()); Logln("Now is: " + text + " (in Japan)"); try { DateTime date = jdf.Parse(text); Logln("But is this not the date?: " + date); c.SetTime(date); int thenYear = c.Get(IBM.ICU.Util.Calendar.YEAR); Logln("Then year: " + thenYear); if (thenYear != nowYear) { Errln("Nowyear " + nowYear + " is not thenyear " + thenYear); } else { Logln("Nowyear " + nowYear + " == thenyear " + thenYear); } } catch (ILOG.J2CsMapping.Util.ParseException ex) { Console.Error.WriteLine(ex.StackTrace); } }
/// <summary> /// Open intent Video Camera when the request code of result is 513 /// </summary> public void OpenIntentVideoCamera() { try { if (Methods.MultiMedia.IsCameraAvailable()) { Intent intent = new Intent(MediaStore.ActionVideoCapture); File mediaFile; try { mediaFile = CreateVideoFile(); } catch (Exception ex) { string timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").Format(new Date()); mediaFile = new File(Methods.Path.FolderDcimVideo + "/" + timeStamp + ".mp4"); CurrentVideoPath = mediaFile.AbsolutePath; // Error occurred while create ... Methods.DisplayReportResultTrack(ex); } if (mediaFile != null) { //var videoUri = FileProvider.GetUriForFile(Context, Context.PackageName + ".fileprovider", mediaFile); //intent.PutExtra(MediaStore.ExtraOutput, videoUri); } Context.StartActivityForResult(intent, 513); } else { Toast.MakeText(Context, Context.GetText(Resource.String.Lbl_Camera_Not_Available), ToastLength.Short)?.Show(); } } catch (Exception e) { Methods.DisplayReportResultTrack(e); } }
/// <summary>Write a node to output.</summary> /// <remarks> /// Write a node to output. /// Node information includes path, modification, permission, owner and group. /// For files, it also includes size, replication and block-size. /// </remarks> /// <exception cref="System.IO.IOException"/> internal static void WriteInfo(Path fullpath, HdfsFileStatus i, XMLOutputter doc) { SimpleDateFormat ldf = df.Get(); doc.StartTag(i.IsDir() ? "directory" : "file"); doc.Attribute("path", fullpath.ToUri().GetPath()); doc.Attribute("modified", ldf.Format(Sharpen.Extensions.CreateDate(i.GetModificationTime ()))); doc.Attribute("accesstime", ldf.Format(Sharpen.Extensions.CreateDate(i.GetAccessTime ()))); if (!i.IsDir()) { doc.Attribute("size", i.GetLen().ToString()); doc.Attribute("replication", i.GetReplication().ToString()); doc.Attribute("blocksize", i.GetBlockSize().ToString()); } doc.Attribute("permission", (i.IsDir() ? "d" : "-") + i.GetPermission()); doc.Attribute("owner", i.GetOwner()); doc.Attribute("group", i.GetGroup()); doc.EndTag(); }
public void TestTextWithDateFormatSecondArg() { System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("en-US"); ValueEval numArg = new NumberEval(321.321); ValueEval formatArg = new StringEval("dd:MM:yyyy hh:mm:ss"); ValueEval[] args = { numArg, formatArg }; ValueEval result = TextFunction.TEXT.Evaluate(args, -1, (short)-1); ValueEval testResult = new StringEval("16:11:1900 07:42:14"); Assert.AreEqual(testResult.ToString(), result.ToString()); // this line is intended to compute how "November" would look like in the current locale String november = new SimpleDateFormat("MMMM").Format(new DateTime(2010, 11, 15)); formatArg = new StringEval("MMMM dd, yyyy"); args[1] = formatArg; result = TextFunction.TEXT.Evaluate(args, -1, (short)-1); testResult = new StringEval(november + " 16, 1900"); Assert.AreEqual(testResult.ToString(), result.ToString()); }
public void SettingCoverExport() { try { File file = new File(DictoryPath, "Setting.config"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); string date = sdf.Format(new Java.Util.Date(file.LastModified())); BufferedReader br = new BufferedReader(new FileReader(file)); var SettingJson = br.ReadLine(); var settings = SettingJson.FromJson <IList <Setting> >(); dataService.SaveAddSettings(settings, true); textViewTips.Text = "参数设置导入成功"; } catch (Exception ex) { textViewTips.Text = "参数设置导入失败" + ex.Message; } }
public void LightCoverExport() { try { File file = new File(DictoryPath, "Light.config"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); string date = sdf.Format(new Java.Util.Date(file.LastModified())); BufferedReader br = new BufferedReader(new FileReader(file)); var LightGroupJson = br.ReadLine(); var LightGroups = LightGroupJson.FromJson <IList <LightExamItem> >(); dataService.SaveLightExamItems(LightGroups, false); textViewTips.Text = "灯光导入成功"; } catch (Exception ex) { textViewTips.Text = "灯光导入失败" + ex.Message; } }
public void TestTextWithDateFormatSecondArg() { // Test with Java style M=Month CultureShim.SetCurrentCulture("en-US"); ValueEval numArg = new NumberEval(321.321); ValueEval formatArg = new StringEval("dd:MM:yyyy hh:mm:ss"); ValueEval[] args = { numArg, formatArg }; ValueEval result = TextFunction.TEXT.Evaluate(args, -1, (short)-1); ValueEval testResult = new StringEval("16:11:1900 07:42:14"); Assert.AreEqual(testResult.ToString(), result.ToString()); // Excel also supports "m before h is month" formatArg = new StringEval("dd:mm:yyyy hh:mm:ss"); args[1] = formatArg; result = TextFunction.TEXT.Evaluate(args, -1, (short)-1); testResult = new StringEval("16:11:1900 07:42:14"); //Assert.AreEqual(testResult.ToString(), result.ToString()); // this line is intended to compute how "November" would look like in the current locale string november = new SimpleDateFormat("MMMM").Format(new DateTime(2010, 11, 15), CultureInfo.CurrentCulture); // Again with Java style formatArg = new StringEval("MMMM dd, yyyy"); args[1] = formatArg; //fix error in non-en Culture Npoi.Core.SS.Formula.Functions.Text.Formatter = new Npoi.Core.SS.UserModel.DataFormatter(CultureInfo.CurrentCulture); result = TextFunction.TEXT.Evaluate(args, -1, (short)-1); testResult = new StringEval(november + " 16, 1900"); Assert.AreEqual(testResult.ToString(), result.ToString()); // And Excel style formatArg = new StringEval("mmmm dd, yyyy"); args[1] = formatArg; result = TextFunction.TEXT.Evaluate(args, -1, (short)-1); testResult = new StringEval(november + " 16, 1900"); Assert.AreEqual(testResult.ToString(), result.ToString()); }
/// <summary> /// Formats a number or date cell, be that a real number, or the /// answer to a formula /// </summary> /// <param name="cell">The cell.</param> /// <param name="value">The value.</param> /// <returns></returns> private String FormatNumberDateCell(CellValueRecordInterface cell, double value) { // Get the built in format, if there is one int formatIndex = ft.GetFormatIndex(cell); String formatString = ft.GetFormatString(cell); if (formatString == null) { return(value.ToString(CultureInfo.InvariantCulture)); } else { // Is it a date? if (Npoi.Core.SS.UserModel.DateUtil.IsADateFormat(formatIndex, formatString) && Npoi.Core.SS.UserModel.DateUtil.IsValidExcelDate(value)) { // Java wants M not m for month formatString = formatString.Replace('m', 'M'); // Change \- into -, if it's there formatString = formatString.Replace("\\\\-", "-"); // Format as a date DateTime d = Npoi.Core.SS.UserModel.DateUtil.GetJavaDate(value, false); SimpleDateFormat df = new SimpleDateFormat(formatString); return(df.Format(d, CultureInfo.CurrentCulture)); } else { if (formatString == "General") { // Some sort of wierd default return(value.ToString(CultureInfo.InvariantCulture)); } // Format as a number DecimalFormat df = new DecimalFormat(formatString); return(df.Format(value, CultureInfo.CurrentCulture)); } } }
/// <summary> /// Open intent Camera when the request code of result is 503 /// </summary> public void OpenIntentCamera() { try { Intent takePictureIntent = new Intent(MediaStore.ActionImageCapture); // Ensure that there's a camera activity to handle the intent var packageManager = takePictureIntent.ResolveActivity(Context.PackageManager); if (packageManager != null) { // Create the File where the photo should go File photoFile = null; try { photoFile = CreateImageFile(); } catch (Exception ex) { string timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").Format(new Date()); photoFile = new File(Methods.Path.FolderDcimImage + "/" + timeStamp + ".jpg"); CurrentVideoPath = photoFile.AbsolutePath; // Error occurred while create ... Console.WriteLine(ex); } // Continue only if the File was successfully created if (photoFile != null) { var photoUri = FileProvider.GetUriForFile(Context, Context.PackageName + ".fileprovider", photoFile); takePictureIntent.PutExtra(MediaStore.ExtraOutput, photoUri); } Context.StartActivityForResult(takePictureIntent, 503); } } catch (Exception e) { Console.WriteLine(e); } }
public void DatewiseLoadDate() { SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat fromUser = new SimpleDateFormat("dd-MM-yyyy"); d1 = txtSurvatichiTarikh.Text; d2 = txtShewatchiTarikh.Text; d1 = d1.Replace("/", "-"); d2 = d2.Replace("/", "-"); String[] data = d2.Split('-'); d2 = Convert.ToString(Convert.ToInt32(data[0]) + 1) + "-" + data[1] + "-" + data[2]; String tstart = "", tend = ""; try { tstart = myFormat.Format(fromUser.Parse(d1)); tend = myFormat.Format(fromUser.Parse(d2)); var db = new SQLiteConnection(filename); var data1 = db.Query <customer_master>("SELECT customer_master.FullName, customer_master.Address,customer_master.Contact_No,GirviMaster.receipt_no,GirviMaster.interset_rate,GirviMaster.Amount, GirviMaster.Date_of_deposit,GirviMaster.forwardstatus,datetime(substr(Date_of_deposit, 7, 4) || '-' || substr(Date_of_deposit, 4, 2) || '-' || substr(Date_of_deposit, 1, 2)) AS SomeDate ,GirviMaster.khatawani_No, GirviMaster.duration, GirviMaster.GirviRecordNo,customer_master.PageNo FROM customer_master INNER JOIN GirviMaster ON customer_master.khatawani_No = GirviMaster.khatawani_No WHERE (status='unchange') and SomeDate >= DATE('" + tstart + "') AND SomeDate <= DATE('" + tend + "') order by SomeDate desc ").ToList(); Result = data1; mListView.Adapter = new GirviDailyReportAdapter(this, Result); } catch (ParseException e1) { e1.PrintStackTrace(); } }
private static void RunAssertionDatetimeBaseTypes( RegressionEnvironment env, bool soda, AtomicLong milestone) { var fields = "c0,c1,c2,c3,c4,c5,c6,c7,c8".SplitCsv(); var builder = new SupportEvalBuilder("MyDateType") .WithExpression(fields[0], "cast(yyyymmdd,System.DateTimeOffset,dateformat:\"yyyyMMdd\")") .WithExpression(fields[1], "cast(yyyymmdd,System.DateTime,dateformat:\"yyyyMMdd\")") .WithExpression(fields[2], "cast(yyyymmdd,long,dateformat:\"yyyyMMdd\")") .WithExpression(fields[3], "cast(yyyymmdd,System.Int64,dateformat:\"yyyyMMdd\")") .WithExpression(fields[4], "cast(yyyymmdd,dateTimeEx,dateformat:\"yyyyMMdd\")") .WithExpression(fields[5], "cast(yyyymmdd,dtx,dateformat:\"yyyyMMdd\")") .WithExpression(fields[6], "cast(yyyymmdd,datetime,dateformat:\"yyyyMMdd\").get(\"month\")") .WithExpression(fields[7], "cast(yyyymmdd,dtx,dateformat:\"yyyyMMdd\").get(\"month\")") .WithExpression(fields[8], "cast(yyyymmdd,long,dateformat:\"yyyyMMdd\").get(\"month\")"); var formatYYYYMMdd = new SimpleDateFormat("yyyyMMdd"); var dateYYMMddDate = formatYYYYMMdd.Parse("20100510"); var dtxYYMMddDate = DateTimeEx.GetInstance(TimeZoneInfo.Utc, dateYYMMddDate); IDictionary <string, object> values = new Dictionary <string, object>(); values.Put("yyyymmdd", "20100510"); builder.WithAssertion(values) .Expect( fields, dateYYMMddDate.DateTime, // c0 dateYYMMddDate.DateTime.DateTime, // c1 dateYYMMddDate.UtcMillis, // c2 dateYYMMddDate.UtcMillis, // c3 dtxYYMMddDate, // c4 dtxYYMMddDate, // c5 5, // c6 5, // c7 5); // c8 builder.Run(env); env.UndeployAll(); }
public void Run(RegressionEnvironment env) { var sdf = new SimpleDateFormat("dd-M-yyyy"); var date = sdf.Parse("22-09-2018"); var epl = "@public @buseventtype @JsonSchemaField(Name=myDate, adapter='" + typeof(MyDateJSONParser).FullName + "')\n" + "create json schema JsonEvent(myDate Date);\n" + "@Name('s0') select * from JsonEvent;\n"; env.CompileDeploy(epl).AddListener("s0"); env.SendEventJson("{\"myDate\" : \"22-09-2018\"}", "JsonEvent"); Assert.AreEqual(date, env.Listener("s0").AssertOneGetNew().Get("myDate")); var renderer = env.Runtime.RenderEventService.GetJSONRenderer(env.Runtime.EventTypeService.GetBusEventType("JsonEvent")); Assert.AreEqual("{\"hello\":{\"myDate\":\"22-09-2018\"}}", renderer.Render("hello", env.Listener("s0").AssertOneGetNewAndReset())); env.UndeployAll(); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public void execute(org.camunda.bpm.engine.delegate.DelegateExecution execution) throws Exception public virtual void execute(DelegateExecution execution) { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss SSS"); // We set the time to check of the updated time is picked up in the history DateTime updatedDate = sdf.parse("01/01/2001 01:23:46 000"); ClockUtil.CurrentTime = updatedDate; execution.setVariable("aVariable", "updated value"); execution.setVariable("bVariable", 123); execution.setVariable("cVariable", 12345L); execution.setVariable("dVariable", 1234.567); execution.setVariable("eVariable", (short)12); DateTime theDate = sdf.parse("01/01/2001 01:23:45 678"); execution.setVariable("fVariable", theDate); execution.setVariable("gVariable", new SerializableVariable("hello hello")); execution.setVariable("hVariable", ";-)".GetBytes()); }
/// <summary> /// creates a /// <see cref="Sharpen.SimpleDateFormat">Sharpen.SimpleDateFormat</see> /// for the requested format string. /// </summary> /// <param name="pattern"> /// a non-<code>null</code> format String according to /// <see cref="Sharpen.SimpleDateFormat">Sharpen.SimpleDateFormat</see> /// . The format is not checked against /// <code>null</code> since all paths go through /// <see cref="DateUtils">DateUtils</see> /// . /// </param> /// <returns> /// the requested format. This simple dateformat should not be used /// to /// <see cref="Sharpen.SimpleDateFormat.ApplyPattern(string)">apply</see> /// to a /// different pattern. /// </returns> public static SimpleDateFormat FormatFor(string pattern) { SoftReference <IDictionary <string, SimpleDateFormat> > @ref = ThreadlocalFormats.Get (); IDictionary <string, SimpleDateFormat> formats = @ref.Get(); if (formats == null) { formats = new Dictionary <string, SimpleDateFormat>(); ThreadlocalFormats.Set(new SoftReference <IDictionary <string, SimpleDateFormat> >(formats )); } SimpleDateFormat format = formats.Get(pattern); if (format == null) { format = new SimpleDateFormat(pattern, CultureInfo.InvariantCulture); format.SetTimeZone(Sharpen.Extensions.GetTimeZone("GMT")); formats.Put(pattern, format); } return(format); }
public override View GetSampleContent(Context con1) { con = con1; SamplePageContent(con); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH mm ss"); currentDateandTime = simpleDateFormat.Format(new Java.Util.Date()); SevenSegmentLayout(); FourteenSegmentLayout(); SixteenSegmentLayout(); MatrixSegmentLayout(); //Main View LinearLayout mainDigitalGaugeLayout = GetView(con); ScrollView mainView = new ScrollView(con); mainView.AddView(mainDigitalGaugeLayout); return(mainView); }
private void OnSave() { if (ValidateData()) { Intent data = new Intent(); data.PutExtra(EXTRA_OPTION, Option); data.PutExtra(EXTRA_WORK_ORDER, WorkOrder.Text); data.PutExtra(EXTRA_COST_CENTER, CostCenter.Text); data.PutExtra(EXTRA_MATERIAL, Material.Text); data.PutExtra(EXTRA_PLANT, Plant.Text); data.PutExtra(EXTRA_STORAGE_LOCATION, StorageLocation.Text); data.PutExtra(EXTRA_BIN, Bin.Text); // TODO: manage format conversion for quantity as string data.PutExtra(EXTRA_QUANTITY, Quantity.Text); SimpleDateFormat ft = new SimpleDateFormat("dd/MM/yy HH:mm:ss", Locale.Us); data.PutExtra(EXTRA_DATE, ft.Format(new Date())); data.PutExtra(EXTRA_INVENTORY, Inventory.Text); data.PutExtra(EXTRA_VENDOR, Vendor.Text); SetResult(Result.Ok, data); // save data for next use ISharedPreferences sharedPref = GetPreferences(FileCreationMode.Private); ISharedPreferencesEditor editor = sharedPref.Edit(); editor.PutString(EXTRA_WORK_ORDER, WorkOrder.Text); editor.PutString(EXTRA_COST_CENTER, CostCenter.Text); editor.PutString(EXTRA_INVENTORY, Inventory.Text); editor.PutString(EXTRA_PLANT, Plant.Text); editor.PutString(EXTRA_STORAGE_LOCATION, StorageLocation.Text); editor.PutString(EXTRA_VENDOR, Vendor.Text); editor.Apply(); // finish activity Finish(); } else { Snackbar.Make(FindViewById(Resource.Id.fab), Resource.String.save_error, Snackbar.LengthLong).Show(); } }
// @SuppressLint("SimpleDateFormat") private void UpdateTimeTab() { if (_isClientSpecified24HourTime) { SimpleDateFormat formatter; if (_is24HourTime) { formatter = new SimpleDateFormat("HH:mm"); _slidingTabLayout.SetTabText(1, formatter.Format(_calendar.Time)); } else { formatter = new SimpleDateFormat("h:mm aa"); _slidingTabLayout.SetTabText(1, formatter.Format(_calendar.Time)); } } else // display time using the device's default 12/24 hour format preference { _slidingTabLayout.SetTabText(1, Android.Text.Format.DateFormat.GetTimeFormat(_context).Format(_calendar.TimeInMillis)); } }
public string date_difference(DateTime current_date, DateTime second_date) { SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); Date date1 = sdf.Parse(current_date.ToString()); Date date2 = sdf.Parse(second_date.ToString()); if (date1.After(date2)) { return("Time out"); } // before() will return true if and only if date1 is before date2 else if (date1.Before(date2)) { TimeSpan span = (second_date - current_date); string time_left = span.Days + "(days) " + span.Hours + "(hrs.) " + span.Minutes + "(min. )"; return(time_left); } else { return(""); } }
/** * 保存错误信息到文件中 * * @param ex * @return 返回文件名称 */ private string saveCrashInfo2File(Throwable ex) { StringBuffer sb = new StringBuffer(); sb.Append("---------------------sta--------------------------"); foreach (var entry in infos) { string key = entry.Key; string value = entry.Value; sb.Append(key + "=" + value + "\n"); } Writer writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); ex.PrintStackTrace(printWriter); Throwable cause = ex.Cause; while (cause != null) { cause.PrintStackTrace(printWriter); cause = cause.Cause; } printWriter.Close(); string result = writer.ToString(); sb.Append(result); sb.Append("--------------------end---------------------------"); LogUtils.e(sb.ToString()); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); string fileName = format.Format(new Date()) + ".log"; File file = new File(FileUtils.createRootPath(mContext) + "/log/" + fileName); FileUtils.createFile(file); FileUtils.writeFile(file.AbsolutePath, sb.ToString()); // uploadCrashMessage(sb.ToString()); return(null); }
/// <summary> /// Set up a 24 hour calendar /// </summary> /// <param name="calendar"></param> private void SetupCalendar(ProjectCalendar calendar) { // Simple date format for setting dates SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm"); // Date range containing all hours DateRange range = new DateRange(format.parse("2000-01-01 00:00"), format.parse("2000-01-02 00:00")); // Set calendar name to the same value to which the project calendar will be set calendar.Name = PROJECT_CALENDER_NAME; // Mark each day as working calendar.setWorkingDay(Day.SUNDAY, true); calendar.setWorkingDay(Day.MONDAY, true); calendar.setWorkingDay(Day.TUESDAY, true); calendar.setWorkingDay(Day.WEDNESDAY, true); calendar.setWorkingDay(Day.THURSDAY, true); calendar.setWorkingDay(Day.FRIDAY, true); calendar.setWorkingDay(Day.SATURDAY, true); // Add a working hours range to each day ProjectCalendarHours hours; hours = calendar.addCalendarHours(Day.SUNDAY); hours.addRange(range); hours = calendar.addCalendarHours(Day.MONDAY); hours.addRange(range); hours = calendar.addCalendarHours(Day.TUESDAY); hours.addRange(range); hours = calendar.addCalendarHours(Day.WEDNESDAY); hours.addRange(range); hours = calendar.addCalendarHours(Day.THURSDAY); hours.addRange(range); hours = calendar.addCalendarHours(Day.FRIDAY); hours.addRange(range); hours = calendar.addCalendarHours(Day.SATURDAY); hours.addRange(range); }
public static bool updateDate(PongEvent paramPongEvent, Session paramSession) { EncryptedStringUserType.Key = CryptUtil.Instance.encryptHexString("oasj419][f'ar;;34").ToCharArray(); System.Collections.IList list = paramSession.createQuery("from ConcLicenseTable").list(); XStream xStream = new XStream(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyyMMddHHmmssZ"); bool @bool = false; foreach (ConcLicenseTable concLicenseTable in list) { LicenseRowItem licenseRowItem = (LicenseRowItem)xStream.fromXML(concLicenseTable.HashKey); if (licenseRowItem.CheckedIn && licenseRowItem.Serial.Equals(paramPongEvent.Serial) && licenseRowItem.Userid.Equals(paramPongEvent.UserId, StringComparison.OrdinalIgnoreCase)) { @bool = true; string str1 = simpleDateFormat.format(DateTime.Now); licenseRowItem.CheckedInDate = str1; string str2 = xStream.toXML(licenseRowItem); concLicenseTable.HashKey = str2; paramSession.update(concLicenseTable); } } return(@bool); }
/// <summary>Create a writer of a local file.</summary> /// <exception cref="System.IO.IOException"/> public static PrintWriter CreateWriter(FilePath dir, string prefix) { CheckDirectory(dir); SimpleDateFormat dateFormat = new SimpleDateFormat("-yyyyMMdd-HHmmssSSS"); for (; ;) { FilePath f = new FilePath(dir, prefix + dateFormat.Format(Sharpen.Extensions.CreateDate (Runtime.CurrentTimeMillis())) + ".txt"); if (!f.Exists()) { return(new PrintWriter(new OutputStreamWriter(new FileOutputStream(f), Charsets.Utf8 ))); } try { Sharpen.Thread.Sleep(10); } catch (Exception) { } } }
private DateTime parseTimestampStringToDate(MedicationSchedule ms) { DateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") { TimeZone = TimeZone.GetTimeZone("UTC") }; var date = new DateTime(); try { date = DateTime.Parse(ms.Timestampstring); DateFormat pstFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS") { TimeZone = TimeZone.GetTimeZone("PST") }; Log.Error(Log_Tag, "timestampstring parsed" + date.ToLocalTime().ToString()); } catch (ParseException e) { e.PrintStackTrace(); } return(date.ToLocalTime()); }
/// <summary> /// Formats a number or date cell, be that a real number, or the /// answer to a formula /// </summary> /// <param name="cell">The cell.</param> /// <param name="value">The value.</param> /// <returns></returns> private String FormatNumberDateCell(CellValueRecordInterface cell, double value) { // Get the built in format, if there is one int formatIndex = ft.GetFormatIndex(cell); String formatString = ft.GetFormatString(cell); if (formatString == null) { return value.ToString(CultureInfo.InvariantCulture); } else { // Is it a date? if (LF.Utils.NPOI.SS.UserModel.DateUtil.IsADateFormat(formatIndex, formatString) && LF.Utils.NPOI.SS.UserModel.DateUtil.IsValidExcelDate(value)) { // Java wants M not m for month formatString = formatString.Replace('m', 'M'); // Change \- into -, if it's there formatString = formatString.Replace("\\\\-", "-"); // Format as a date DateTime d = LF.Utils.NPOI.SS.UserModel.DateUtil.GetJavaDate(value, false); SimpleDateFormat df = new SimpleDateFormat(formatString); return df.Format(d); } else { if (formatString == "General") { // Some sort of wierd default return value.ToString(CultureInfo.InvariantCulture); } // Format as a number DecimalFormat df = new DecimalFormat(formatString); return df.Format(value); } } }
public SynchronizedTask(CountDownLatch main, CountDownLatch gate, AtomicLong count, SimpleDateFormat format) { this.format = format; this.count = count; this.gate = gate; this.main = main; }
/// <summary> /// Gets a file where to store the picture. /// </summary> private static File GetOutputMediaFile() { var mediaStorageDir = new File(Environment.GetExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "dot42 Simple Camera"); if (!mediaStorageDir.Exists()) { if (!mediaStorageDir.Mkdirs()) { Log.E("dot42 Simple Camera", "failed to create directory"); return null; } } // Create a media file name var timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").Format(new Date()); var mediaFile = new File(mediaStorageDir.Path + File.Separator + "IMG_" + timeStamp + ".jpg"); return mediaFile; }
public void Run() { long start = System.currentTimeMillis(); try { gate.countDown(); gate.await(); Date date = new Date(); for(int i = 0; i < COUNT; i++) { String value = new SimpleDateFormat(format).format(date); Date copy = new SimpleDateFormat(format).parse(value); AssertEquals(date, copy); } }catch(Exception e) { assertTrue(false); } finally { count.getAndAdd(System.currentTimeMillis() - start); main.countDown(); } }
/// <summary> /// Compute the date format for storing in the static variable dateFormat_. /// </summary> /// public static SimpleDateFormat getDateFormat() { SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyyMMddHHmmss'Z'"); dateFormat.setTimeZone(System.Collections.TimeZone.getTimeZone("UTC")); return dateFormat; }
private ValueEval TryParseDateTime(double s0, string s1) { try { FormatBase dateFormatter = new SimpleDateFormat(s1); //first month of java Gregorian Calendar month field is 0 DateTime dt = new DateTime(1899, 12, 30, 0, 0, 0); dt = dt.AddDays((int)Math.Floor(s0)); double dayFraction = s0 - Math.Floor(s0); dt = dt.AddMilliseconds((int)Math.Round(dayFraction * 24 * 60 * 60 * 1000)); return new StringEval(dateFormatter.Format(dt)); } catch (Exception) { return ErrorEval.VALUE_INVALID; } }
/// <summary>Use the simple date formatter to read the date from a string </summary> private static System.DateTime parseDate(System.String input) { //UPGRADE_NOTE: Final was removed from the declaration of 'df '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" //UPGRADE_ISSUE: Class 'java.text.SimpleDateFormat' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javatextSimpleDateFormat'" //UPGRADE_ISSUE: Constructor 'java.text.SimpleDateFormat.SimpleDateFormat' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javatextSimpleDateFormat'" SimpleDateFormat df = new SimpleDateFormat(DateFactory.DATE_FORMAT_MASK); try { return System.DateTime.Parse(input, df); } //UPGRADE_TODO: Class 'java.text.ParseException' was converted to 'System.FormatException' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javatextParseException'" catch (System.FormatException e) { throw new System.ArgumentException("Invalid date input format: [" + input + "] it should follow: [" + DateFactory.DATE_FORMAT_MASK + "]"); } }
/// <summary> /// Constructor for the <c>DateFormat</c> object. This will /// wrap a simple date format, providing access to the conversion /// functions which allow date to string and string to date. /// </summary> /// <param name="format"> /// this is the pattern to use for the date type /// </param> public DateFormat(String format) { this.format = new SimpleDateFormat(format); }
public MessageAdapter(Activity activity) { mInflater = activity.LayoutInflater; mMessages = new List<Pair<Message, int?>>(); mFormatter = new SimpleDateFormat("HH:mm"); }
/** * Default handler of Entity Time requests (XEP-0202). Unless overridden, * this method returns the current local time as specified by the XEP. * * @param iq * Entity Time request stanza. * @return Result stanza including the local current time. */ protected virtual IQ handleEntityTime(IQ iq) { DateTime now = DateTime.Now; SimpleDateFormat sdf = new SimpleDateFormat(XMPPConstants.XMPP_DATETIME_FORMAT); SimpleDateFormat sdf_timezone = new SimpleDateFormat("Z"); String utc = sdf.format(now); String tz = sdf_timezone.format(new Date()); String tzo = new StringBuilder(tz).insert(3, ':').toString(); IQ result = IQ.createResultIQ(iq); Element el = result.setChildElement("time", NAMESPACE_ENTITY_TIME); el.addElement("tzo").setText(tzo); el.addElement("utc").setText(utc); return result; }
/** * Convert time in milliseconds to string with format yyyy-MM-dd HH:mm:ss. * * @param milis Milliseconds * * @return String of time */ public static string timeMilisToString(long milis) { SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(milis); return sd.format(calendar.getTime()); }
/** * Convert time in milliseconds to string with format yyyy-MM-dd HH:mm:ss. * * @param milis Milliseconds * * @return String of time */ public static string timeMilisToString(long milis, string format) { SimpleDateFormat sd = new SimpleDateFormat(format); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(milis); return sd.format(calendar.getTime()); }
/** * Convert date to string with default format yyyy-MM-dd * * @param date Date to convert * * @return String of date. */ public static string dateToString(DateTime date) { DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); return df.format(date); }
public static string GetDateTimeNow(string format) { Calendar currentDefaultCalendar = Calendar.GetInstance(Locale.Default); SimpleDateFormat enviromentFormat = new SimpleDateFormat(format); return enviromentFormat.Format(currentDefaultCalendar); }
public override void onReceive(int channelId, sbyte[] data) { if (outerInstance.mConnectionHandler == null) { return; } DateTime calendar = new GregorianCalendar(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd aa hh:mm:ss.SSS"); string timeStr = " " + dateFormat.format(calendar); string strToUpdateUI = StringHelperClass.NewString(data); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final String message = strToUpdateUI.concat(timeStr); string message = strToUpdateUI + timeStr; new Thread(() => { try { outerInstance.mConnectionHandler.send(MULTIACCESSORY_CHANNEL_ID, message.GetBytes()); } catch (IOException e) { Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); } }).start(); }
public override String ToString() { String s = "Certificate name:\n"; s += " " + getName().toUri() + "\n"; s += "Validity:\n"; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss"); dateFormat.setTimeZone(System.Collections.TimeZone.getTimeZone("UTC")); String notBeforeStr = dateFormat.format(net.named_data.jndn.util.Common .millisecondsSince1970ToDate((long) Math.Round(notBefore_,MidpointRounding.AwayFromZero))); String notAfterStr = dateFormat.format(net.named_data.jndn.util.Common .millisecondsSince1970ToDate((long) Math.Round(notAfter_,MidpointRounding.AwayFromZero))); s += " NotBefore: " + notBeforeStr + "\n"; s += " NotAfter: " + notAfterStr + "\n"; for (int i = 0; i < subjectDescriptionList_.Count; ++i) { CertificateSubjectDescription sd = (CertificateSubjectDescription) subjectDescriptionList_[i]; s += "Subject Description:\n"; s += " " + sd.getOidString() + ": " + sd.getValue() + "\n"; } s += "Public key bits:\n"; Blob keyDer = key_.getKeyDer(); String encodedKey = net.named_data.jndn.util.Common.base64Encode(keyDer.getImmutableArray()); for (int i_0 = 0; i_0 < encodedKey.Length; i_0 += 64) s += encodedKey.Substring(i_0,(Math.Min(i_0 + 64,encodedKey.Length))-(i_0)) + "\n"; if (extensionList_.Count > 0) { s += "Extensions:\n"; for (int i_1 = 0; i_1 < extensionList_.Count; ++i_1) { CertificateExtension ext = (CertificateExtension) extensionList_[i_1]; s += " OID: " + ext.getOid() + "\n"; s += " Is critical: " + ((ext.getIsCritical()) ? 'Y' : 'N') + "\n"; s += " Value: " + ext.getValue().toHex() + "\n"; } } return s; }
/** * Convert date to string. * * @param date Date to convert * @param format Date format * * @return String of date */ public static string dateToString(DateTime date, string format) { DateFormat df = new SimpleDateFormat(format); Return df.format(date); }
/// <summary> /// Sets the default date. /// </summary> private void SetDefaultDate() { ApplicationData.CurrentDate = string.Empty; Date cDate = new Date(); var curDate = new SimpleDateFormat(GetString(Resource.String.DateFormat)).Format(cDate); fromDate.Text = curDate; toDate.Text = curDate; }
/// <summary> /// Creates a temp image file in order to obtain a valid Uri. /// </summary> /// <returns></returns> private Java.IO.File createImageFile() { // Create an image file name string timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").Format(new Java.Util.Date()); string imageFileName = "JPEG_" + timeStamp + "_"; Java.IO.File storageDir = Android.OS.Environment.GetExternalStoragePublicDirectory( Android.OS.Environment.DirectoryPictures); if (!storageDir.Exists()) { storageDir.Mkdir(); } Java.IO.File image = Java.IO.File.CreateTempFile( imageFileName, /* prefix */ ".jpg", /* suffix */ storageDir /* directory */ ); return image; }
public static string ToString(DateTime value, string format) { var simpleDateFormat = new SimpleDateFormat(ToJavaFormat(format), Locale.US); var result = simpleDateFormat.Format(value.ToDate()); if (format.EndsWith("zzz")) { var tempResult = result; result = tempResult.Substring(0, tempResult.Length - 2) + ":" + tempResult.Substring(tempResult.Length - 2); } return result; }
/** * @param dateFormat pass <code>null</code> for default YYYYMMDD * @return <code>null</code> if timeStr is <code>null</code> */ private static Double ConvertDate(String dateStr, SimpleDateFormat dateFormat) { if (dateStr == null) { return Double.NaN; } DateTime dateVal; if (dateFormat == null) { dateVal = HSSFDateUtil.ParseYYYYMMDDDate(dateStr); } else { try { dateVal = DateTime.Parse(dateStr, CultureInfo.CurrentCulture); } catch (FormatException e) { throw new InvalidOperationException("Failed to parse date '" + dateStr + "' using specified format '" + dateFormat + "'", e); } } return HSSFDateUtil.GetExcelDate(dateVal); }
/* * Convert string time to milliseconds log * * @param time String to convert with format yyyy-MM-dd HH:mm:ss * * @return milliseconds */ public static long timeStringToMilis(string time) { long milis = 0; try { SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); DateTime date = sd.parse(time); milis = date.getTime(); } catch (Exception e) { e.printStackTrace(); } return milis; }
/** * Constructor. The date format that is passed should comply to the standard * Java date formatting conventions * * @param format the date format */ public DateFormat(string format) : base(format) { // Verify that the format is valid SimpleDateFormat df = new SimpleDateFormat(format); }