public void setOutlookFields(DateTime startDate, DateTime endDate, string room, DateTime startTime, DateTime endTime) { //Set To: field DateTime dateTimeStart; //String a = " 04:00 A.M"; String test = startDate.ToLongDateString(); String test2 = startDate.ToShortTimeString(); String test4 = startDate.ToLongTimeString(); String test3 = startDate.ToShortTimeString(); dateTimeStart = DateTime.Parse(startDate.Month.ToString() + "/" + startDate.Day.ToString() + "/" + startDate.Year.ToString() +" "+ startTime.Hour +":" + startTime.Minute +":" + startTime.Second+"." + startTime.Millisecond); DateTime dateTimeEnd; dateTimeEnd = DateTime.Parse(endDate.Month.ToString() + "/" + endDate.Day.ToString() + "/" + endDate.Year.ToString() + " " + endTime.Hour + ":" + endTime.Minute + ":" + endTime.Second + "." + endTime.Millisecond); //if (dateTimeStart > dateTimeEnd) //{ //} //else //{ (Globals.ThisAddIn.Application.ActiveInspector().CurrentItem as Outlook.AppointmentItem).StartInStartTimeZone = dateTimeStart; (Globals.ThisAddIn.Application.ActiveInspector().CurrentItem as Outlook.AppointmentItem).EndInEndTimeZone = dateTimeEnd; (Globals.ThisAddIn.Application.ActiveInspector().CurrentItem as Outlook.AppointmentItem).Location = room; //} }
public Event_Rep( int eventID, DateTime startTime, DateTime endTime, string keyframePath, string comment, bool loadImage) { this.eventID = eventID; this.startTime = startTime; this.endTime = endTime; this.eventDuration = endTime - startTime; this.comment = comment; this.shortComment = GetStringStart(comment, 15); this.keyframePath = keyframePath; this.borderColour = DefaultKeyframeBorderColour; //format time string for UI if (startTime.Hour < 12) { this.strTime = startTime.ToShortTimeString() + " am"; } else { this.strTime = startTime.ToShortTimeString() + " pm"; } this.eventLength = Daily_Annotation_Summary.SecondsToString( (int)eventDuration.TotalSeconds); if (loadImage) { this.keyframeSource = Image_Rep.GetImgBitmap(keyframePath, false); } }
public static HtmlString LogItemDate(DateTime p_Date) { if (p_Date >= DateTime.Today) { return new HtmlString(p_Date.ToShortTimeString()); } if (p_Date >= DateTime.Today.AddDays(-1)) { return new HtmlString("Yesterday, " + p_Date.ToShortTimeString()); } if (p_Date >= DateTime.Today.AddDays(-7)) { return new HtmlString(p_Date.ToString("dddd") + ", " + p_Date.ToShortTimeString()); } if (p_Date >= DateTime.Today.AddYears(-1)) { return new HtmlString(p_Date.ToString("dd MMM") + ", " + p_Date.ToShortTimeString()); } if (p_Date == DateTime.MinValue) { return new HtmlString(""); } return new HtmlString(p_Date.ToString("dd MMM yy") + ", " + p_Date.ToShortTimeString()); }
public EvidencijaTreningaIzvestaj(Nullable<int> clanId, DateTime from, DateTime to, List<Grupa> grupe) { this.clanId = clanId; Title = "Dolazak na trening"; string subtitle; if (from.Date == to.Date) { subtitle = from.ToLongDateString(); subtitle += " " + from.ToShortTimeString() + " - " + to.ToShortTimeString(); } else { subtitle = from.ToShortDateString() + " " + from.ToShortTimeString(); subtitle += " - " + to.ToShortDateString() + " " + to.ToShortTimeString(); } SubTitle = subtitle; DocumentName = Title; clanFont = new Font("Arial", 10, FontStyle.Bold); itemFont = new Font("Courier New", 9); Font itemsHeaderFont = null; Font groupTitleFont = new Font("Courier New", 10, FontStyle.Bold); lista = new EvidencijaTreningaLista(clanId, from, to, grupe, this, 1, 0f, itemFont, itemsHeaderFont, groupTitleFont); }
public void PrintFormats(DateTime dateTime) { Log("dateTime.ToShortDateString(): " + dateTime.ToShortDateString()); Log("dateTime.ToShortTimeString(): " + dateTime.ToShortTimeString()); Log("dateTime.ToLongTimeString(): " + dateTime.ToLongTimeString()); Log("dateTime.ToShortTimeString(): " + dateTime.ToShortTimeString()); Log("dateTime.ToString(): " + dateTime.ToString()); Log("DateTimeSerializer.ToShortestXsdDateTimeString(dateTime): " + DateTimeSerializer.ToShortestXsdDateTimeString(dateTime)); Log("DateTimeSerializer.ToDateTimeString(dateTime): " + DateTimeSerializer.ToDateTimeString(dateTime)); Log("DateTimeSerializer.ToXsdDateTimeString(dateTime): " + DateTimeSerializer.ToXsdDateTimeString(dateTime)); Log("\n"); }
/// <summary> /// Sets up the entry for the schedule /// </summary> /// <param name="previousTaskEnd">The time where the task before this ended</param> /// <param name="duration"></param> /// <param name="taskDescription"></param> public void SetEntry(DateTime previousTaskEnd, TimeSpan duration, string taskDescription) { previousEnd = previousTaskEnd; Duration = duration; description.Content = taskDescription; time.Content = previousTaskEnd.ToShortTimeString(); }
public void AddUser(string jsonString) { using (var session = FluentNHibernateConfiguration.InitFactory.sessionFactory.OpenSession()) { using (var transaction = session.BeginTransaction()) { JObject jsonObject = JObject.Parse(jsonString); var user = new Entities.Member { memberFirstName = jsonObject.SelectToken("firstName").ToString(), memberLastName = jsonObject.SelectToken("lastName").ToString(), userName = jsonObject.SelectToken("userName").ToString(), memberPassword = jsonObject.SelectToken("password").ToString(), memberEmail = jsonObject.SelectToken("email").ToString() }; JavaScriptSerializer js = new JavaScriptSerializer(); DateTime dt = new DateTime(); user.memberHash = util.UtilityMethods.CalculateMD5Hash(user.userName + dt.ToShortTimeString()); Context.Response.Write(js.Serialize(new Response3 { LogIn = 1, twocubeSSO = user.memberHash })); session.Save(user); transaction.Commit(); } } }
public Query AddParam(string name, DateTime value) { m_command.Parameters.Add(name, SqlDbType.DateTime); m_command.Parameters[name].Value = value.ToShortDateString() + " " + value.ToShortTimeString(); return this; }
public PartialViewResult AjoutFormulaireTravail(DateTime debut, DateTime fin, int id_employe) { var typesTravail = from travail in cnx.type_temps where (travail.absence == false) select new { nomTravail = travail.nom, id_type_travail = travail.id_type_temps }; ViewBag.type_travail = new SelectList(typesTravail, "id_type_travail", "nomTravail", 2); var projets = from p in cnx.projet where ( p.z_actif == true) select new { nomProjet = p.reference + " " + p.nom + " / " + p.client.nom, id_projet = p.id_projet }; ViewBag.id_projet = new SelectList(projets, "id_projet", "nomProjet"); var emp = cnx.employe.Where(e => e.id_employe == id_employe).Single(); var taches = from task in cnx.tache select new { id_tache = task.id_tache, nom_tache = task.nom_tache }; ViewBag.id_tache = new SelectList(taches, "id_tache", "nom_tache", emp.id_tache); TravailView travailview = new TravailView(); travailview.id_employe = id_employe; travailview.dateTravail = debut; travailview.debutTravail = debut.ToShortTimeString(); travailview.finTravail = fin.ToShortTimeString(); return PartialView("_formTravail", travailview); }
public static void Main() { string msg1 = "The date and time patterns are defined in the DateTimeFormatInfo \n" + "object associated with the current thread culture.\n"; // Initialize a DateTime object. Console.WriteLine("Initialize the DateTime object to May 16, 2001 3:02:15 AM.\n"); DateTime myDateTime = new System.DateTime(2001, 5, 16, 3, 2, 15); // Identify the source of the date and time patterns. Console.WriteLine(msg1); // Display the name of the current culture. CultureInfo ci = Thread.CurrentThread.CurrentCulture; Console.WriteLine("Current culture: \"{0}\"\n", ci.Name); // Display the long date pattern and string. Console.WriteLine("Long date pattern: \"{0}\"", ci.DateTimeFormat.LongDatePattern); Console.WriteLine("Long date string: \"{0}\"\n", myDateTime.ToLongDateString()); // Display the long time pattern and string. Console.WriteLine("Long time pattern: \"{0}\"", ci.DateTimeFormat.LongTimePattern); Console.WriteLine("Long time string: \"{0}\"\n", myDateTime.ToLongTimeString()); // Display the short date pattern and string. Console.WriteLine("Short date pattern: \"{0}\"", ci.DateTimeFormat.ShortDatePattern); Console.WriteLine("Short date string: \"{0}\"\n", myDateTime.ToShortDateString()); // Display the short time pattern and string. Console.WriteLine("Short time pattern: \"{0}\"", ci.DateTimeFormat.ShortTimePattern); Console.WriteLine("Short time string: \"{0}\"\n", myDateTime.ToShortTimeString()); }
public static void Main() { // Initialize a DateTime object. Console.WriteLine("Initialize the DateTime object to May 16, 2001 3:02:15 AM.\n"); DateTime dateAndTime = new System.DateTime(2001, 5, 16, 3, 2, 15); // Display the name of the current culture. Console.WriteLine($"Current culture: \"{CultureInfo.CurrentCulture.Name}\"\n"); var dtfi = CultureInfo.CurrentCulture.DateTimeFormat; // Display the long date pattern and string. Console.WriteLine($"Long date pattern: \"{dtfi.LongDatePattern}\""); Console.WriteLine($"Long date string: \"{dateAndTime.ToLongDateString()}\"\n"); // Display the long time pattern and string. Console.WriteLine($"Long time pattern: \"{dtfi.LongTimePattern}\""); Console.WriteLine($"Long time string: \"{dateAndTime.ToLongTimeString()}\"\n"); // Display the short date pattern and string. Console.WriteLine($"Short date pattern: \"{dtfi.ShortDatePattern}\""); Console.WriteLine($"Short date string: \"{dateAndTime.ToShortDateString()}\"\n"); // Display the short time pattern and string. Console.WriteLine($"Short time pattern: \"{dtfi.ShortTimePattern}\""); Console.WriteLine($"Short time string: \"{dateAndTime.ToShortTimeString()}\"\n"); }
//otomatik bağlan işe yaramaması yada bir den çok com port bulunma durumunakarşı hazırlanan kısım //com bortu ve baud rate yi manuel girerek saat bilgisini arduino ya gönderir private void button2_Click(object sender, EventArgs e) { if (serialPort1.IsOpen) serialPort1.Close(); serialPort1.PortName = Interaction.InputBox("COM PORT GİRİNİZ: "); int baudRate; if (System.Int32.TryParse(Interaction.InputBox("BAUD RATE GİRİNİZ: "), out baudRate)) { serialPort1.BaudRate = baudRate; try { serialPort1.Open(); } catch (Exception ex) { MessageBox.Show(ex.Message, "HATA", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { MessageBox.Show("Geçerli Baud Rate Giriniz!", "HATA", MessageBoxButtons.OK, MessageBoxIcon.Error); } if (serialPort1.IsOpen) { zaman = DateTime.Now; serialPort1.Write(zaman.ToShortTimeString() + zaman.Second.ToString() + "|"); serialPort1.Close(); } }
private DataRow CriarDocumento(DataTable tabelaDocumento, DateTime data) { var linha = CriarDocumento(tabelaDocumento); linha["data"] = string.Format("{0} {1}", data.ToShortDateString(), data.ToShortTimeString()); return linha; }
public virtual void Repaint(InventoryNoticeMessage message) { this.showTime = (int)message.duration; this.dateTime = message.time; if (string.IsNullOrEmpty(message.title) == false) { if (this.title != null) { this.title.text = string.Format(message.title, message.parameters); this.title.color = message.color; } } else title.gameObject.SetActive(false); this.message.text = string.Format(message.message, message.parameters); this.message.color = message.color; if (this.time != null) { this.time.text = dateTime.ToShortTimeString(); this.time.color = message.color; } }
public VoiceMailEntry(WebVoiceMailControl owner, InfoFile info) { mOwner = owner; InitializeComponent(); Dock = DockStyle.Top; this.progressBar.EndWaiting(); this.progressBar.Enabled = false; this.progressBar.Visible = false; mFileInfo = info; lFrom.Text = mFileInfo.From; DateTime dateTime = new DateTime(1970, 1, 1); dateTime = dateTime.AddSeconds(mFileInfo.Time); lDate.Text = dateTime.ToShortDateString() + " " + dateTime.ToShortTimeString(); tbTagIt.Text = mFileInfo.Tags; //Setup Color Scheme mCached = mFileInfo.Cached; if (mCached) { mFileInfo.FileName = Path.GetFileName(mFileInfo.FileName); } this.Name = mFileInfo.FileName; this.toolTip.SetToolTip(this.lFrom, mFileInfo.From); this.toolTip.SetToolTip(this.pMailImage, mFileInfo.Location.ToString()); ResetButtonDesign(); }
public Trace(string traceName, DateTime created, int number) { Name = traceName; gen = created; pts = number; LineTwo = created.ToShortDateString() + " " + created.ToShortTimeString() + " | " + number + " pts"; _name = Name; _lineTwo = LineTwo; }
void AddNewRow(int position, System.Data.DataRow row) { ListViewItem lvi = new ListViewItem(); lvi.Name = (position + 1).ToString(); lvi.Text = (position + 1).ToString(); int vid = 0; if (!System.Convert.IsDBNull(row["VendorID"])) vid = (int)row["VendorID"]; string vendor = ""; if (!System.Convert.IsDBNull(row["VendorName"])) vendor = (string)row["VendorName"]; string vtype = ""; if (!System.Convert.IsDBNull(row["VendorType"])) vtype = ((int)row["VendorType"]).ToString(); // byte[] logo = null; // if (!System.Convert.IsDBNull(row["Logo"])) logo = (byte[])row["Logo"]; DateTime cr_dtm = new DateTime(1900, 1, 1); if (!System.Convert.IsDBNull(row["Created"])) cr_dtm = ((DateTime)row["Created"]); lvi.SubItems.Add(vid.ToString()); lvi.SubItems.Add(vendor); lvi.SubItems.Add(vtype); // lvi.SubItems.Add(logo); lvi.SubItems.Add(""); lvi.SubItems.Add(cr_dtm.ToShortDateString() + " " + cr_dtm.ToShortTimeString()); this.lvVendors.Items.Add(lvi); return; }
public static void Main() { string futureDate = "01/05/2010"; System.DateTime today = System.DateTime.Now; Console.WriteLine("Today is : " + today.ToShortDateString()); Console.WriteLine("Current time is: " + today.ToShortTimeString()); Console.WriteLine("A week from now is: " + today.AddDays(7).ToShortDateString()); Console.WriteLine("Day is: " + today.DayOfWeek.ToString()); //Parse date and write out the year component Console.WriteLine("\r\nFuture Date Year: "); Console.WriteLine(System.DateTime.Parse(futureDate).Year.ToString()); //Generate custom format Console.WriteLine(System.DateTime.Parse(futureDate).ToString("dddd, MMMM yyyy ")); //TryParseExact() DateTime date; bool status = DateTime.TryParseExact("Nov 21 11:34:17 2010", "MMM d HH:mm:ss yyyy", null, DateTimeStyles.AllowInnerWhite | DateTimeStyles.AllowWhiteSpaces, out date); if (status) { Console.WriteLine(date.ToLongDateString()); } else { Console.WriteLine("Unable to write out date using TryParseExact()"); } Console.ReadLine(); }
public string GetDateString(System.DateTime date) { if (string.IsNullOrEmpty(Format) == false) { return(date.ToString(Format)); } if (stringType == DateTimeStringType.ToString) { return(date.ToString()); } else if (stringType == DateTimeStringType.ToLongDateString) { return(date.ToLongDateString()); } else if (stringType == DateTimeStringType.ToLongTimeString) { return(date.ToLongTimeString()); } else if (stringType == DateTimeStringType.ToShortDateString) { return(date.ToShortDateString()); } else if (stringType == DateTimeStringType.ToShortTimeString) { return(date.ToShortTimeString()); } return(date.ToString()); }
//public void agregarHorario(int dia,DateTime desde,DateTime hasta) public void agregarHorario(int idHorario,int fila,DateTime horaDesde,DateTime horaHasta) { horarios.Add(idHorario,new HorarioAuxiliar(idHorario, horaDesde, horaHasta)); TimeSpan diferencia = horaHasta - horaDesde; float diferenciaHoras = (float)diferencia.Hours + ((float)diferencia.Minutes / (float)60); float diferenciaInicioYHoradesde = (float)horaDesde.Hour + ((float)horaDesde.Minute / (float)60) - this.horaDesde; Control pan = tlpHorariosDias.GetControlFromPosition(0, fila); Button button = new Button(); button.BackColor = Color.DarkOrchid;; button.Name = idHorario.ToString(); float anchoHorarios = pan.Width; float diferenciaHorasComponente = this.horaHasta - this.horaDesde; float anchoHora = pan.Width / diferenciaHorasComponente; button.Height = (int)(pan.Height); button.Width = (int)(diferenciaHoras * anchoHora); button.Top = 0; button.Left = (int)(diferenciaInicioYHoradesde * anchoHora + this.desplazamiento); button.MouseHover += new EventHandler(mostrarHora); button.MouseLeave += new EventHandler(limpiarLabel); System.Windows.Forms.ToolTip ToolTip1 = new System.Windows.Forms.ToolTip(); ToolTip1.SetToolTip(button, horaDesde.ToShortTimeString() + " hasta " + horaHasta.ToShortTimeString()); pan.Controls.Add(button); }
static void Main() { DateTime timeBeer = new DateTime(); Console.Write("Enter time: "); bool isValid = DateTime.TryParse(Console.ReadLine(), out timeBeer); if (isValid) { Console.WriteLine("Is it beer time?"); Console.WriteLine(timeBeer.ToShortTimeString()); TimeSpan daytime = timeBeer.TimeOfDay; TimeSpan endBeertime = new TimeSpan(3, 00, 00); TimeSpan startBeertime = new TimeSpan(13, 00, 00); if ((daytime < endBeertime) || (daytime >= startBeertime)) { Console.WriteLine("IT IS BEER TIMEEEEEEEEEEEE!"); } else { Console.WriteLine("NON-BEER TIME"); } } else { Console.WriteLine("Invalid time"); } }
public string unixConvert(double x) { System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); dateTime = dateTime.AddSeconds(x); string printDate = dateTime.ToString("dd/M/yyyy", null) + " " + dateTime.ToShortTimeString(); return(printDate); }
public IEnumerable<Shipment> GetDelivery(long companyId, long sobId, string deliveryNo, DateTime date) { List<Shipment> list = this.Context.Shipments.Where(x => x.CompanyId == companyId && x.SOBId == sobId && x.DeliveryNo == deliveryNo).ToList(); list = list.Where(x => Convert.ToDateTime(x.DeliveryDate).ToShortDateString() == date.ToShortDateString() && Convert.ToDateTime(x.DeliveryDate).ToShortTimeString() == date.ToShortTimeString()).ToList(); return list; }
public void RestartTime() { time = time.AddMinutes(30.0); TimerText.text = time.ToShortTimeString(); Time.timeScale = 1; DayCompletedCanvas.SetActive(false); bHasDayFinished = false; }
/* Adds two watermarks: one using a pdf file and a the second text. * You can use the stamp.pdf file in the TestFiles directory. */ private void addWatermarkButton_Click(object sender, EventArgs e) { String filter = "PDF Files (*.pdf)|*.PDF|" + "All files (*.*)|*.*"; String filename = chooseFile(filter); if (filename != null && g_AVDoc.IsValid()) { CAcroPDDoc pdDoc = (CAcroPDDoc)g_AVDoc.GetPDDoc(); //Acquire the Acrobat JavaScript Object interface from the PDDoc object Object jsObj = pdDoc.GetJSObject(); /* Add a watermark from a file. * See the readme for a discussion on InvokeMember. * function prototype: * addWatermarkFromFile(cDIPath, nSourcePage, nStart, nEnd, bOnTop, bOnScreen, bOnPrint, nHorizAlign, nVertAlign, nHorizValue, nVertValue, bPercentage, nScale, bFixedPrint, nRotation, nOpacity) */ object[] addFileWatermarkParam = { filename, 0, 0, 0, true, true, true, 0, 3, 10, -10, false, 0.4, false, 0, 0.7 }; Type T = jsObj.GetType(); T.InvokeMember( "addWatermarkFromFile", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, jsObj, addFileWatermarkParam); //get current time and make a string from it System.DateTime currentTime = System.DateTime.Now; /* make a color object */ Object colorObj = T.InvokeMember( "color", BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance, null, jsObj, null); Type colorType = colorObj.GetType(); Object blueColorObj = colorType.InvokeMember( "blue", BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance, null, colorObj, null); /* Add a text watermark. * ' function prototype: * ' addWatermarkFromText(cText, nTextAlign, cFont, nFontSize, color, nStart, nEnd, bOnTop, bOnScreen, bOnPrint, nHorizAlign, nVertAlign, nHorizValue, nVertValue, bPercentage, nScale, bFixedPrint, nRotation, nOpacity) */ object[] addTextWatermarkParam = { currentTime.ToShortTimeString(), 1, "Helvetica", 100, blueColorObj, 0, 0, true, true, true, 0, 3, 20, -45, false, 1.0, false, 0, 0.7 }; T.InvokeMember( "addWatermarkFromText", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, jsObj, addTextWatermarkParam); } }
protected virtual void tm_workthread_proc(object state) { System.DateTime now = System.DateTime.Now; string value = now.ToShortTimeString(); System.Console.WriteLine("{0} Запись в БД -------------------------", now); if (this.conn == null) { this.conn = new System.Data.SqlClient.SqlConnection(this.sb.ToString()); } else if (this.conn.ConnectionString == null) { this.conn = new System.Data.SqlClient.SqlConnection(this.sb.ToString()); } else if (this.conn.ConnectionString == "") { this.conn = new System.Data.SqlClient.SqlConnection(this.sb.ToString()); } try { this.conn.Open(); if (this.cmd == null) { this.InitSql(); } using (this.conn) { this.tr = this.conn.BeginTransaction(); this.cmd.Connection = this.conn; this.cmd.Transaction = this.tr; foreach (System.Data.DataRow dataRow in this._tVals.Rows) { try { if (System.Convert.ToString(dataRow["Value"]).Contains("Ошибка:")) { throw new System.Exception(System.Convert.ToString(dataRow["Value"]).Replace("Ошибка:", "")); } this.cmd.Parameters["time"].Value = value; this.cmd.Parameters["tag_id"].Value = dataRow["TagId"]; this.cmd.Parameters["val"].Value = dataRow["Value"]; this.cmd.ExecuteNonQuery(); } catch (System.Exception ex) { System.Diagnostics.Trace.WriteLine(string.Format("Ошибка записи в БД: {0}. Тег {1}:{2}", ex.Message, dataRow["TagId"], dataRow["TagName"])); } } this.tr.Commit(); this.lastSuccessTransaction = now; System.Console.WriteLine("Завершение транзакции -------------------", System.DateTime.Now); } } catch (System.Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message); } }
public static string ToShortDateTime(DateTime date, bool twoLines) { var sb = new StringBuilder(); sb.Append(date.ToShortDateString()); sb.Append(twoLines ? "<br />" : " "); sb.Append(date.ToShortTimeString()); sb.Append(date.IsDaylightSavingTime() ? " (pdt)" : " (pst)"); return sb.ToString(); }
public ChatMessageInfoItem(string message, DateTime date) { InitializeComponent(); _date = date; label1.Text = message; label2.Text = date.ToShortTimeString(); }
/// <summary> /// Date format /// </summary> /// <param name="dtDate"></param> /// <returns>stringDate</returns> protected string formatDate(DateTime dtDate) { //Get date and time in short format string stringDate = ""; stringDate = dtDate.ToShortDateString().ToString() + " " + dtDate.ToShortTimeString().ToString(); return stringDate; }
/// <summary> /// Converter from ending time to strings /// </summary> public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { EventViewModel model = value as EventViewModel; string str = wpweeklyplanner.AppResources.DetailsEnds; DateTime now = DateTime.Now; DateTime time = new DateTime(now.Year, now.Month, now.Day, model.StartHour + model.Duration, 0, 0); return String.Format(str, time.ToShortTimeString()); }
//@MyHTML.date("Date", @Model.Accident.Date, "Įvykio data ir laikas (vietos laiku)", "require().match('date').lessThanOrEqualTo(new Date())", true) public static MvcHtmlString date(string id, DateTime Val, string Title, Int32 Tip, string Validity, string UpdateField) { string ValStr = Val.ToShortDateString().Replace(".", "-") + " / " + Val.ToShortTimeString().Substring(0, 5); return MvcHtmlString.Create(String.Format(@"<div class='Top-form-label'>{2}</div> <input type='text' id='{0}' title='{2}' class='date ui-widget-content ui-corner-all {3} {5}' data-ctrl='{{""Tip"":""{1}"",""Validity"":""{4}"",""Type"":""date"",""Value"":""{1}""{6}}}' value='{1}'/>" , (id), ValStr, Title, (Tip == 1) ? "defaultText" : "", Validity, (UpdateField != "") ? "UpdateField" : "", (UpdateField != "") ? ",\"UpdateField\":\"" + UpdateField + "\"" : "")); // 0 1 2 3 4 5 //"2010-10-01 / 14:22" }
public static string FormatFuzzyDateString( DateTime dt ) { if ( dt.Ticks == 0 ) return "Never"; DateTime now = DateTime.Now;// +( new TimeSpan( 340, 0, 0, 0 ) ); for ( int i = 0; i < 7; ++i ) { DateTime dayToTest = now - ( new TimeSpan( i, 0, 0, 0 ) ); if ( IsSameDay( dt, dayToTest ) ) { switch ( i ) { case 0: return "Today at " + dt.ToShortTimeString(); case 1: return "Yesterday"; default: return i + " days ago"; } } } for ( int i = 0; i < 3; ++i ) { DateTime weekToTest = now - ( new TimeSpan( ( int )now.DayOfWeek, 0, 0, 0 ) ) - ( new TimeSpan( i * 7, 0, 0, 0 ) ); if ( IsSameWeek( dt, weekToTest ) ) { switch ( i ) { case 0: return "Last week"; default: return ( i + 1 ) + " weeks ago"; } } } for ( int i = 0; i < 11; ++i ) { DateTime startOfMonth = now - ( new TimeSpan( now.Day - 1, 0, 0, 0 ) ); DateTime toTest = ( now - ( new TimeSpan( now.Day - 1, 0, 0, 0 ) ) ) - ( new TimeSpan( GetDaysSinceMonthBefore( startOfMonth, i + 1 ), 0, 0, 0 ) ); if ( IsSameMonth( dt, toTest ) ) { switch ( i ) { case 0: return "Last month"; default: return ( i + 1 ) + " months ago"; } } } return "Over a year ago"; }
/// <summary> /// 保存 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnSave_Click(object sender, EventArgs e) { bool success = false; for (int i = 1; i <= 12; i++) { HtmlInputText text1 = (HtmlInputText)this.FindControl("a"+i.ToString()); HtmlInputText text2 = (HtmlInputText)this.FindControl("b" + i.ToString()); HtmlInputText text3 = (HtmlInputText)this.FindControl("c" + i.ToString()); HtmlInputText text4 = (HtmlInputText)this.FindControl("d" + i.ToString()); MCT.Nub = i; if (ddlSys.SelectedValue == "1")//夏季,规定数据库中前12项存夏季时间,后12项存冬季时间 { MCT.ID = i; } else { MCT.ID =i + 12; } MCT.季节 =int.Parse(ddlSys.SelectedValue.ToString()); DateTime temp = new DateTime(); if (!DateTime.TryParse(text1.Value + ":" + text2.Value, out temp))//一种传参方式,可以在外面使用temp { temp = DateTime.Now;//转换失败,取当前时间 } MCT.STime=DateTime.Parse(temp.ToShortTimeString()); DateTime temp2 = new DateTime(); if (!DateTime.TryParse(text3.Value + ":" + text4.Value, out temp2)) { temp2 = DateTime.Now; } MCT.ETime =DateTime.Parse(temp2.ToShortTimeString());//2009-3-10 7:00 //MCT.STime = DateTime.Parse(text1.Value + ":" + text2.Value); // 开始时间 //MCT.ETime =DateTime.Parse( text3.Value +":"+ text4.Value);//结束时间 try { ET.Update(MCT); success = true; } catch(Exception ex) { throw ex; } } if (success == true) { Common.JShelper.JSAlert(this.Page, "", "更新成功!"); InitBind(int.Parse(ddlSys.SelectedValue.ToString())); } else { Common.JShelper.JSAlert(this.Page, "", "更新失败!"); } }
public static string ConvertToDate(DateTime dt) { string result = string.Empty; result = dt.ToShortDateString() + "T" + dt.ToShortTimeString() + "Z"; //2008-07-17T09:24:17Z return result; }
// // The ugly details of building the Html // private string FormatDate (DateTime dt) { TimeSpan age = DateTime.Now - dt; // FIXME: Saner date formatting if (age.TotalHours < 18) return dt.ToShortTimeString (); if (age.TotalDays < 180) return dt.ToString ("MMM d, h:mm tt"); return dt.ToString ("MMM d, yyyy"); }
public void TestMethod_Date_Time_Spaces_Around_Text() { DateTime now = DateTime.Now; DateTime dateRemind = new DateTime(2012, 06, 01, 15, 20, 0); DateTime date; string leftText; Assert.IsTrue(TextParser.Parse(" Susitikimas 2012.06.01 15:20 ", out date, out leftText)); Assert.AreEqual(dateRemind.ToShortDateString(), date.ToShortDateString()); Assert.AreEqual(dateRemind.ToShortTimeString(), date.ToShortTimeString()); Assert.AreEqual("Susitikimas", leftText); }
/// <summary> /// Gets the timeframe respect to the creation date of a signal /// </summary> /// <param name="creationDate">The creation date.</param> /// <returns></returns> public static string GetTimeframe(DateTime creationDate) { TimeSpan ts = DateTime.Now.Subtract(creationDate); if (ts.Days > 60) { return "circa 1 mese fa (il " + creationDate.ToShortDateString() + ")"; } if (ts.Days > 31) { return "circa " + (ts.Days / 30).ToString() + " mesi fa (il " + creationDate.ToShortDateString() + ")"; } if (ts.Days > 1) { return ts.Days.ToString() + " giorni fa alle " + creationDate.ToShortTimeString(); } if (ts.Days == 1) { return "ieri alle " + creationDate.ToShortTimeString(); } if (ts.Days == 0 && ts.Hours > 1) { return ts.Hours.ToString() + " ore e " + ts.Minutes.ToString() + " minuti fa"; } if (ts.Days == 0 && ts.Hours == 1) { return "1 ora e " + ts.Minutes.ToString() + " minuti fa"; } if (ts.Minutes <= 1) return "circa 1 minuto fa"; if (ts.Minutes > 1) return ts.Minutes.ToString() + " minuti fa"; return "pochi secondi fa"; }
/// <summary> /// Convert UNIX timestamp to System.DateTime /// </summary> /// <param name="time">UNIX timestamp in seconds from 1970, 1, 1, 0, 0, 0, 0</param> /// <returns>DateTime date</returns> public DateTime FromUnixToSystemDateTime(string time) { double timestamp = double.Parse(time); var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0); unixEpoch = unixEpoch.AddSeconds(timestamp); var date = DateTime.Parse(unixEpoch.ToShortDateString() + " " + unixEpoch.ToShortTimeString()); return date; }
public string GetHead() { return("" + "Table[" + Table + "]" + " Request[" + RequestType + "] " + " Response[" + ResponseType + "]" + " ->[" + ToSizeString(SizeRequest) + "]" + " <-[" + ToSizeString(SizeResponse) + "]" + " at " + Date.ToShortTimeString() + "." ); }
private void Start() { data = System.DateTime.Now; hora = System.DateTime.Now; data.ToShortDateString(); hora.ToShortTimeString(); caminhoDiretorioRelatorios = "C:/Relatórios - Arrasta!"; criaDiretorioRelatorios(); }
/// <summary> /// Get date from Unix timestamp /// </summary> /// <param name="ts">Timestamp</param> /// <returns>A string with format dd/mm/yyyy hh:mm:ss</returns> public static string getDateTime(long ts) { System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); // Add the number of seconds in UNIX timestamp to be converted. dateTime = dateTime.AddSeconds(ts); // The dateTime now contains the right date/time so to format the string, // use the standard formatting methods of the DateTime object. return(dateTime.ToShortDateString() + " " + dateTime.ToShortTimeString()); }
public static string ConvertUNIXToDateTime(double ut) { double timestamp = ut; System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); dateTime = dateTime.AddSeconds(timestamp); string printDate = dateTime.ToShortDateString() + " " + dateTime.ToShortTimeString(); return(printDate); }
/// <summary> /// Convert a UTC file timestamp to a local string representation /// </summary> protected string ConvertUNIXTime(int timeStamp) { // First make a System.DateTime equivalent to the UNIX Epoch. System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); // Add the number of seconds in UNIX timestamp to be converted. dateTime = dateTime.AddSeconds(timeStamp); // The dateTime now contains the right date/time so to format the string, // use the standard formatting methods of the DateTime object. return(dateTime.ToShortDateString() + " " + dateTime.ToShortTimeString()); }
public string GetDiagString() { string msg = "Start: " + start.ToShortTimeString() + " End: "; if (end > DateTime.Now) { msg += "RUNNING"; } else { msg += end.ToShortTimeString() + " "; } msg += "Duration: " + Duration.ToString(@"dd\.hh\:mm\:ss"); return(msg); }
void DisplayDateTimeFullInfo(System.DateTime dateTime, string title) { MessageBox.Show(title + Environment.NewLine + " ToString()=" + dateTime.ToString() + Environment.NewLine + " ToShortDateString()=" + dateTime.ToShortDateString() + Environment.NewLine + " ToShortTimeString()=" + dateTime.ToShortTimeString() + Environment.NewLine //+ " ToLongTimeString()=" + dateTime.ToLongTimeString() + Environment.NewLine + " ToUniversalTime().ToString()=" + dateTime.ToUniversalTime().ToString() + Environment.NewLine + " ToLocalTime().ToString()=" + dateTime.ToLocalTime().ToString() + Environment.NewLine + " ToUniversalTime().ToLocalTime().ToString()=" + dateTime.ToUniversalTime().ToLocalTime().ToString() + Environment.NewLine + " ToLocalTime().ToUniversalTime().ToString()=" + dateTime.ToLocalTime().ToUniversalTime() + Environment.NewLine + " Hours=" + dateTime.Hour.ToString() + Environment.NewLine + " Minutes=" + dateTime.Minute.ToString() + Environment.NewLine + " Seconds=" + dateTime.Second.ToString() + Environment.NewLine ); }
// Use this for initialization void Awake() { time = System.DateTime.Parse("2005-05-05 8:00 AM"); TimerText.text = time.ToShortTimeString(); CurrentDay = 1; DayText.text = "Day " + CurrentDay.ToString(); MinutesToAdd = 1; PopulationText.text = iPopulation.ToString(); QualitySettings.antiAliasing = 8; Time.timeScale = 0; Allstars = Stars.GetComponentsInChildren <SpriteRenderer>(); Allclouds = Clouds.GetComponentsInChildren <SpriteRenderer>(); }
// Update is called once per frame void Update() { Ray ray = cam.ViewportPointToRay(new Vector3(0.5F, 0.5F, 0)); RaycastHit hit; if (Physics.Raycast(ray, out hit, rayDistance) && data.getSCarbs(hit.collider.tag) != -1) { string tag = hit.collider.tag; Food food = data.getFood(tag); textPoint.text = food.name; textFoodName.text = food.name; textCaloriesRight.text = food.calories.ToString(); textSimpleCarbsRight.text = food.simpleCarbs.ToString(); textComplexCarbsRight.text = food.complexCarbs.ToString(); if (Input.GetMouseButtonDown(0)) { addItemToPlayerStats(tag); textFoodName.text = food.name; } } else { textPoint.text = ""; textFoodName.text = "Food"; textCaloriesRight.text = "0"; textSimpleCarbsRight.text = "0"; textComplexCarbsRight.text = "0"; } if (Input.GetButton("Fire1") && (textPoint.text.CompareTo("") == 0)) { Vector3 naturalForward = Camera.main.transform.forward; naturalForward.y = 0; transform.position = transform.position + naturalForward.normalized * playerSpeed * Time.deltaTime; } textCal.text = Mathf.RoundToInt((float)totalCalories).ToString(); textSCarb.text = Mathf.RoundToInt((float)simpleCarbs).ToString(); textCCarb.text = Mathf.RoundToInt((float)complexCarbs).ToString(); textBloodSugar.text = Mathf.RoundToInt((float)bloodSugar).ToString(); textClock.text = clock.ToShortTimeString(); clock = clock.AddSeconds(timeScale * Time.deltaTime); }
private void Form2_Load(object sender, EventArgs e) { string urlprofile = "https://www.reddit.com/user/{0}/about.json"; string fed = string.Format(urlprofile, labanmetag.Text); System.Net.WebClient wc = new System.Net.WebClient(); byte[] raw = wc.DownloadData(fed); string webData = System.Text.Encoding.UTF8.GetString(raw); dynamic stuff = JsonConvert.DeserializeObject(webData); labanmetag.Text = stuff.data.name; if (stuff.data.is_employee == "True") { lblAdmin.Visible = true; } if (stuff.data.is_mod == "True") { lblMod.Visible = true; } if (stuff.data.is_gold == "True") { lblPremium.Visible = true; } if (stuff.data.subreddit.over_18 == "True") { lblNsfw.Visible = true; } lblKarmaTotal.Text = (stuff.data.total_karma).ToString(); lblKarmaLink.Text = (stuff.data.link_karma).ToString(); lblKarmaComment.Text = (stuff.data.comment_karma).ToString(); lblKarmaAward.Text = (stuff.data.awardee_karma + stuff.data.awarder_karma).ToString(); lblDescription.Text = (stuff.data.subreddit.public_description).ToString(); lblDescription.Text = lblDescription.Text.Replace("\n", ""); double timestamp = stuff.data.created; System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); dateTime = dateTime.AddSeconds(timestamp); string printDate = dateTime.ToShortDateString() + " " + dateTime.ToShortTimeString(); lblCreatedOn.Text = printDate; }
protected override void SolveInstance(IGH_DataAccess DA) { List <string> log = new List <string>(); bool loggedIn = Default.LoggedIn; System.DateTime lastLogin = Default.LastLoggedIn; log.Add("Axis Version Number: " + Assembly.GetExecutingAssembly().GetName().Version); // Check the validity of the login token. (Refactored method) DateTime t0 = DateTime.Now; Auth auth = new Auth(); bool isValid = auth.IsValid; if (isValid) { log.Add("Valid token."); } log.Add(DateTime.Now.Subtract(t0).TotalMilliseconds.ToString()); if (Default.LoggedIn) { log.Add("Logged in."); log.Add("LLI: " + lastLogin.ToLongDateString() + ", " + lastLogin.ToShortTimeString()); DateTime validTo = lastLogin.AddDays(2); int valid = DateTime.Compare(System.DateTime.Now, validTo); if (valid < 0) { log.Add("Login token valid."); log.Add("Valid to: " + validTo.ToLongDateString() + ", " + validTo.ToShortTimeString()); } Default.ValidTo = validTo; } if (loggedIn) { this.Message = "Logged In"; } else { this.Message = "Error"; } DA.SetDataList(0, log); }
/// <summary> /// This method formats the specified date in the EDS standard format. /// </summary> /// <param name="edsDate"></param> /// <param name="showTime"></param> /// <returns></returns> public static string edsDateTime(System.DateTime edsDate, bool showTime) { string myDate; if (edsDate == DateTime.MinValue) { return(string.Empty); } myDate = edsDate.ToString("dd MMM yyyy"); if (showTime == true) { myDate += ", " + edsDate.ToShortTimeString(); } return(myDate); }
static StackObject *ToShortTimeString_1(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject *ptr_of_this_method; StackObject *__ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method); System.DateTime instance_of_this_method = (System.DateTime) typeof(System.DateTime).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); var result_of_this_method = instance_of_this_method.ToShortTimeString(); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method); __intp.Free(ptr_of_this_method); return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method)); }
/// <summary> /// 获取图片操作权限 /// </summary> public string GetImageJsSdk() { try { /* * 参照文档:http://qydev.weixin.qq.com/wiki/index.php?title=%E5%BE%AE%E4%BF%A1JS-SDK%E6%8E%A5%E5%8F%A3 * wx.config({ * debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 * appId: '', // 必填,企业号的唯一标识,此处填写企业号corpid * timestamp: , // 必填,生成签名的时间戳 * nonceStr: '', // 必填,生成签名的随机串 * signature: '',// 必填,签名,见附录1 * jsApiList: [] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2 * }); */ // 1.设置所需的值 string jsapi_ticket = WeChatBase.GetJSapiTicket(); // jsapi凭证 string appId = WeChatBase.GetCorpId(); // 企业ID System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); long timestamp = (long)(DateTime.Now - startTime).TotalMilliseconds; // 时间戳 string nonceStr = startTime.ToShortTimeString(); // 随机字符串 string signature = SecurityHelper.EncryptSha1(string.Format("jsapi_ticket={0}&noncestr={1}×tamp={2}&url={3}", jsapi_ticket, nonceStr, timestamp, Request["url"])); // 2.返回wxconfig对象 var en = new { debug = false, appId = appId, timestamp = timestamp, nonceStr = nonceStr, signature = signature, jsApiList = new List <string>() { "chooseImage", "previewImage", "uploadImage", "downloadImage" }, }; return(SuccessResultData(en)); } catch (Exception ex) { return(FailureResultMsg(ex.Message)); } }
private void TimestampToDate() { System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); foreach (var item in this.UserLeases) { // Console.WriteLine("date "+UnixTimeStampToDateTime(Convert.ToDouble(item.StartValidity))); if (!item.StartValidity.Contains("-") && !item.StartValidity.Contains("/") && !item.StartValidity.Equals("0") && !item.EndValidity.Equals("0")) { dateTime = dateTime.AddSeconds(Convert.ToDouble(item.StartValidity)); string printDate = dateTime.ToShortDateString() + " " + dateTime.ToShortTimeString(); item.StartValidity = printDate; dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); dateTime = dateTime.AddSeconds(Convert.ToDouble(item.EndValidity)); printDate = dateTime.ToShortDateString() + " " + dateTime.ToShortTimeString(); item.EndValidity = printDate; dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); } } }
public void TestTutoril() { var connectionString = "mongodb://[test:1234]@localhost/test"; var client = new MongoClient(connectionString); var server = client.GetServer(); var database = server.GetDatabase("test"); var collection = database.GetCollection <Entity>("entities"); var entity = new Entity { Name = "Tom", Age = 25 }; collection.Insert(entity); //var id = entity.Id; //var query = Query<Entity>.EQ( e => e.Id, id ); //entity = collection.FindOne( query ); //entity.Name = "Dick"; System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); // Add the number of seconds in UNIX timestamp to be converted. dateTime = dateTime.AddSeconds(entity.Id.Timestamp); // The dateTime now contains the right date/time so to format the string, // use the standard formatting methods of the DateTime object. string printDate = dateTime.ToShortDateString() + " " + dateTime.ToShortTimeString(); // Print the date and time System.Console.WriteLine(printDate); entity.Timestamp = printDate; collection.Save(entity); //var update = Update<Entity>.Set( e => e.Name, "Harry" ); //collection.Update( query, update ); //collection.Remove( query ); }
private void button2_Click(object sender, RoutedEventArgs e) { try { WebRequest req_big_time = WebRequest.Create(big_storeurl.Text + "time"); HttpWebRequest httpreq_time = (HttpWebRequest)req_big_time; httpreq_time.Method = "GET"; httpreq_time.ContentType = "text/xml; charset=utf-8"; httpreq_time.Credentials = new NetworkCredential(big_user.Text, big_pass.Text); HttpWebResponse res_time = (HttpWebResponse)httpreq_time.GetResponse(); StreamReader rdr_time = new StreamReader(res_time.GetResponseStream()); string result_time = rdr_time.ReadToEnd(); MessageBox.Show(result_time); if (res_time.StatusCode == HttpStatusCode.OK || res_time.StatusCode == HttpStatusCode.Accepted) { XDocument doc_time = XDocument.Parse(result_time); string stime = doc_time.Element("time").Element("time").Value.ToString(); // File.WriteAllText("server_time.txt", stime); MessageBox.Show(stime); double timestamp = Convert.ToDouble(stime); // First make a System.DateTime equivalent to the UNIX Epoch. System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); // Add the number of seconds in UNIX timestamp to be converted. dateTime = dateTime.AddSeconds(timestamp); // The dateTime now contains the right date/time so to format the string, // use the standard formatting methods of the DateTime object. string printDate = dateTime.ToShortDateString() + " " + dateTime.ToShortTimeString(); MessageBox.Show(printDate); } } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } }
public void SqlConnectionUpdate() { Grid grid = new Grid(); SetupTestGrid(grid); grid.StayEdit = true; grid.CurrentId = "11"; grid.MasterTable.Rows[0]["intTest"].Value = 33345; grid.MasterTable.Rows[0]["decTest"].Value = 5634; grid.MasterTable.Rows[0]["vchTest"].Value = "blah" + DateTime.Now.ToString(dateformat); ((WebGrid.Columns.DateTime)grid.MasterTable.Columns["dtmDate"]).Format = dateformat; DateTime date = DateTime.Now; grid.MasterTable.Rows[0]["dtmDate"].Value = date; grid.MasterTable.Rows[0]["bitFlag"].Value = true; grid.MasterTable.Rows[0]["bitSecondFlag"].Value = false; grid.RaisePostBackEvent("RecordUpdateClick!!False"); Assert.AreEqual(grid.SystemMessage.Count, 0); Assert.AreEqual(grid.Mode, Mode.Edit); grid = new Grid(); SetupTestGrid(grid); grid.StayEdit = true; grid.CurrentId = "11"; ((WebGrid.Columns.DateTime)grid.MasterTable.Columns["dtmDate"]).Format = dateformat; grid.MasterTable.Rows[0]["dtmDate"].Value = DateTime.Now; DateTime?seconddate = grid.MasterTable.Rows[0]["dtmDate"].Value as DateTime?; //The grid should honour the date format and therefor returns a different date time. Assert.AreNotEqual(date, seconddate); //Date should be the same Assert.AreEqual(date.ToShortDateString(), seconddate.Value.ToShortDateString()); //Hour and minutes should also be the same. Assert.AreEqual(date.ToShortTimeString(), seconddate.Value.ToShortTimeString()); }
private void DrawDateTime() { //Using the System.DateTime to collect current time information System.DateTime dateTime = System.DateTime.Now; if (month == "") { month = dateTime.Month.ToString(); } //Displaying all GUI elements using Rect Rect date = new Rect(new Vector2(20, 20), new Vector2(100, 20)); GUI.Label(date, dateTime.ToShortDateString()); Rect time = new Rect(new Vector2(Screen.width - 80, 20), new Vector2(80, 20)); GUI.Label(time, dateTime.ToShortTimeString()); Rect input = new Rect(new Vector2(20, 60), new Vector2(Screen.width - 40, Screen.height / 3 - 140)); Rect outputObject = new Rect(new Vector2(20, 80 + Screen.height / 3 - 140), new Vector2(Screen.width - 40, Screen.height - 240)); currentLog = GUI.TextArea(input, currentLog); string editMode = "------------------------------------EDITING------------------------------------" + "\n"; if (finalPath != "") { if (File.Exists(finalPath)) { GUI.TextArea(outputObject, editMode + File.ReadAllText(finalPath).ToString()); } } Rect inputObject = new Rect(new Vector2(20, Screen.height - 70), new Vector2(Screen.width - 40, 20)); //Allowing input of an object to specify what the log is about (Optional Field) currentObject = (Object)EditorGUI.ObjectField(inputObject, currentObject, typeof(Object)); }
protected string GetTimeString(System.DateTime dateTime) { if (KickStarter.settingsManager.saveTimeDisplay != SaveTimeDisplay.None) { if (KickStarter.settingsManager.saveTimeDisplay == SaveTimeDisplay.CustomFormat) { string creationTime = dateTime.ToString(KickStarter.settingsManager.customSaveFormat); return(" (" + creationTime + ")"); } else { string creationTime = dateTime.ToShortDateString(); if (KickStarter.settingsManager.saveTimeDisplay == SaveTimeDisplay.TimeAndDate) { creationTime += " " + dateTime.ToShortTimeString(); } return(" (" + creationTime + ")"); } } return(string.Empty); }
static void Main(string[] args) { //DateTime System.DateTime myDate = new System.DateTime(); Console.WriteLine(myDate); System.DateTime date1 = new System.DateTime(2020, 11, 27, 12, 54, 52); //year, month, date, hour, minutes, seconds Console.WriteLine(date1); Console.WriteLine(date1.ToShortDateString()); //11/27/2020 Console.WriteLine(date1.ToShortTimeString()); //12:54 PM Console.WriteLine(date1.AddDays(-4)); //11/23/2020 12:54:52 PM System.DateTime dateNow = System.DateTime.Now; Console.WriteLine(dateNow); string formattedDate = string.Format("{0:yyyy-MMMM-d HH:mm:ss tt}", dateNow); //here we use regex MMM -month abbreviation, MMMM - full month name, dddd - day of the week, tt- AM or PM Result: 2020-November-27 01:26:57 AM Console.WriteLine(formattedDate); string formattedDateTwo = string.Format("{0:dddd 'of month' MMMM 'year' yyyy}", date1); //Friday of month November year 2020 Console.WriteLine(formattedDateTwo); }
private void button4_Click(object sender, EventArgs e) { // This is an example of a UNIX timestamp for the date/time 11-04-2005 09:25. //1422100800000 //1113211532 string str = textBox2.Text.Substring(0, 10); double timestamp = Convert.ToDouble(str); // First make a System.DateTime equivalent to the UNIX Epoch. System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); // Add the number of seconds in UNIX timestamp to be converted. dateTime = dateTime.AddSeconds(timestamp); dateTime = dateTime.AddHours(+7); // The dateTime now contains the right date/time so to format the string, // use the standard formatting methods of the DateTime object. string printDate = dateTime.ToShortDateString() + " " + dateTime.ToShortTimeString(); // Print the date and time textBox3.Text = printDate; //System.Console.WriteLine(printDate); }