本文整理汇总了C#中System.DateTime.ToString方法的典型用法代码示例。如果您正苦于以下问题:C# DateTime.ToString方法的具体用法?C# DateTime.ToString怎么用?C# DateTime.ToString使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.DateTime
的用法示例。
在下文中一共展示了DateTime.ToString方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: DateTimeToString
protected string DateTimeToString(DateTime datetime, bool dateOnly)
{
if (dateOnly)
return datetime.ToString("yyyy-MM-dd");
else
return datetime.ToString("yyyy-MM-dd HH:mm:ss.fff");
}
示例2: ClearItemsBeforeDate
/// <summary>
/// Clears all items from the database where their PublishDate is before the date provided.
/// </summary>
/// <param name="date"></param>
public void ClearItemsBeforeDate(DateTime date)
{
try
{
using (SqliteConnection connection = new SqliteConnection(ItemsConnectionString))
{
connection.Open();
using (SqliteCommand command = new SqliteCommand(connection))
{
string sql = @"DELETE FROM items WHERE DATETIME(publishdate) <= DATETIME(@date)";
command.CommandText = sql;
SqliteParameter parameter = new SqliteParameter("@date", DbType.String);
parameter.Value = date.ToString("yyyy-MM-dd HH:mm:ss");
command.Parameters.Add(parameter);
int rows = command.ExecuteNonQuery();
Logger.Info("ClearItemsBeforeDate before {0} cleared {1} rows.", date.ToString("yyyy-MM-dd HH:mm:ss"), rows);
}
}
}
catch (SqliteException e)
{
Logger.Warn("SqliteException occured while clearing items before {0}: \n{1}", date, e);
}
}
示例3: DateDiff
public static string DateDiff(DateTime dt)
{
TimeSpan span = (TimeSpan) (DateTime.Now - dt);
if ((((dt.Year == DateTime.Now.Year) && (dt.Day == DateTime.Now.Day)) && ((dt.Month == DateTime.Now.Month) && (dt.Hour == DateTime.Now.Hour))) && (((span.Seconds < 60) && (span.Hours == 0)) && (span.Minutes == 0)))
{
return "刚刚";
}
if ((((dt.Year == DateTime.Now.Year) && (dt.Day == DateTime.Now.Day)) && ((dt.Month == DateTime.Now.Month) && (span.Minutes < 60))) && (span.Hours == 0))
{
return (span.Minutes + "分钟前");
}
if (((dt.Year == DateTime.Now.Year) && (dt.Day == DateTime.Now.Day)) && ((dt.Month == DateTime.Now.Month) && (span.Hours <= 2)))
{
return (span.Hours + "小时前");
}
if (dt.AddDays(1.0).ToString("yyyy-MM-dd") == DateTime.Now.ToString("yyyy-MM-dd"))
{
return ("昨天" + dt.ToString("HH:mm"));
}
if (((dt.Year == DateTime.Now.Year) && (dt.Day == DateTime.Now.Day)) && ((dt.Month == DateTime.Now.Month) && (span.Hours > 2)))
{
return ("今天" + dt.ToString("HH:mm"));
}
return dt.ToString("yyyy-MM-dd HH:mm:ss");
}
示例4: AddWorkLog
public void AddWorkLog(string issueRef, WorkLogStrategy workLogStrategy, string comment, TimeSpan timeSpent, DateTime logDate, TimeSpan? remainingTime = null)
{
if (logDate.Kind != DateTimeKind.Local) logDate = DateTime.SpecifyKind(logDate, DateTimeKind.Local);
var postData = new Dictionary<string, object>
{
{ "started", $"{logDate.ToString("yyyy-MM-ddTHH:mm:ss.fff")}{logDate.ToString("zzz").Replace(":", "")}"},
{ "comment", comment },
{ "timeSpent", $"{timeSpent.Hours}h {timeSpent.Minutes}m"},
};
var adjustmentMethod = string.Empty;
var newEstimate = string.Empty;
if (remainingTime.HasValue)
{
newEstimate = $"{remainingTime.Value.Hours}h {remainingTime.Value.Minutes}m";
}
switch (workLogStrategy)
{
case WorkLogStrategy.Automatic:
adjustmentMethod = "auto";
break;
case WorkLogStrategy.LeaveRemaining:
adjustmentMethod = "leave";
break;
case WorkLogStrategy.SetValue:
adjustmentMethod = "new";
break;
}
restClient.Post(HttpStatusCode.Created, $"issue/{issueRef}/worklog?adjustEstimate={adjustmentMethod}&newEstimate={newEstimate}&reduceBy=", postData);
}
示例5: SaveEdition
public static int SaveEdition(DateTime dt)
{
try
{
DataSet ds = ExecuteQuery("select id_edition from edition where date_edition='" + dt.ToString() + "'");
if (ds.Tables[0].Rows.Count != 0)
{
return -2;
}
else
{
int q = ExecuteNonQuery("insert into edition (date_edition) values ('" + dt.ToString() + "')");
if (q == -1)
{
return q;
}
else
{
return 1;
}
}
}
catch (Exception e)
{
e.ToString();
return -99;
}
}
示例6: GetConnections
public async Task<SearchResult> GetConnections(string from, string to, DateTime time, bool isArrival = false)
{
// Check for network connectivity
if (!NetworkInterface.GetIsNetworkAvailable()) return null;
var client = new RestClient("http://transport.opendata.ch/v1/");
var request =
new RestRequest("connections")
.AddParameter("from", from)
.AddParameter("to", to)
.AddParameter("date", time.ToString("yyyy-MM-dd"))
.AddParameter("time", time.ToString("HH:mm"))
.AddParameter("isArrivalTime", isArrival ? 1 : 0);
try
{
return
await
client
.ExecutTaskAsync(request)
.ContinueWith(task => JObject.Parse(task.Result.Content).ToObject<SearchResult>());
}
catch (Exception)
{
return null;
}
}
示例7: FirstAfter
public void FirstAfter(DateTime timestamp)
{
using (NpgsqlConnection conn = Connection ()) {
conn.Open ();
Console.WriteLine ("time i'm shooting for: " + timestamp.ToString ());
string timestampStr = timestamp.ToString (dbTimeFormat);
bool forward = true;
bool back = false;
Screenshot screenshot = GetNextPrevNote (conn, timestampStr, forward, timeCheckTypeFilters);
if (screenshot == null) {
Console.WriteLine ("time i'm shooting for: -> note is null");
screenshot = GetNextPrevNote (conn, timestampStr, back, timeCheckTypeFilters);
} else {
Console.WriteLine ("time i'm shooting for: -> note not null");
}
if (screenshot != null) {
currentScreenshot = screenshot;
setNoteDataFileIfAvailible (conn, currentScreenshot);
sendTimeToTimeblockAdder (currentScreenshot);
} else {
Console.WriteLine ("time i'm shooting for: -> note null again");
}
conn.Close ();
}
}
示例8: makeReservation
public bool makeReservation(string sStartCityCode, string sEndCityCode, DateTime dtFlightDate, PassengerInfo[] passengers, PaymentInfo pInfo)
{
Console.WriteLine("Making reservation for {0} to {1} on {2} for {3} Passengers", sStartCityCode, sEndCityCode, dtFlightDate.ToString(), passengers.Count());
if (DateTime.Compare(dtFlightDate, DateTime.Now) <= 0) return false;
List<Flight_DAL.Route> lstRoutes;
bool bStatus = false;
lock (this)
{
lstRoutes = myFlightBLL.getFlightBLLInstance().getFlightsBetweenCities(sStartCityCode, sEndCityCode);
}
if (lstRoutes != null)
{
Console.WriteLine("Obtained the list of routes. Count - " + lstRoutes.Count);
Route r = (from ro in lstRoutes
where ro.FlightTime.Equals(dtFlightDate.ToString("HH:mm"))
select ro).FirstOrDefault();
if (r != null)
{
Console.WriteLine("Obtained the route information");
List<Passenger> lstPassengers = getPassengerList(passengers);
string sReservationID;
lock (this)
{
sReservationID = myFlightBLL.getFlightBLLInstance().reserveFlight(r.RouteID, dtFlightDate, lstPassengers);
bStatus = myFlightBLL.getFlightBLLInstance().makePayment(sReservationID, getPaymentDetails(pInfo));
}
}
}
return bStatus; //default value
}
示例9: ProcessDayForecastCollection
private void ProcessDayForecastCollection(int daysInMonth, DateTime dateTimeItem, IList<DayForecast> dateTimeCollection)
{
for (var i = 1; i <= daysInMonth; i++)
{
bool canAddDay = true;
var dayForecastItem = new DateTime(dateTimeItem.Year, dateTimeItem.Month, i);
if (_dayForecastConfiguration != null)
{
if(_dayForecastConfiguration.WeekDaysToExclude != null)
{
string day = dayForecastItem.ToString("dddd");
if (_dayForecastConfiguration.WeekDaysToExclude.Contains(day))
canAddDay = false;
}
}
if (canAddDay)
{
_totalDays++;
dateTimeCollection.Add(new DayForecast
{
FullDayOfTheWeek = dayForecastItem.ToString("dddd"),
FullMonth = dayForecastItem.ToString("MMMM"),
Year = dayForecastItem.Year,
DayOfTheMonth = dayForecastItem.Day,
ShortDayOfTheWeek = dayForecastItem.ToString("ddd"),
ShortMonth = dayForecastItem.ToString("MMM"),
TotalHours = _dayForecastConfiguration.DefaultHoursInDay,
TotalMinutes = _dayForecastConfiguration.DefaultHoursInDay * 60,
TotalSeconds = (_dayForecastConfiguration.DefaultHoursInDay * 60) * 60
});
}
}
}
示例10: LogItemDate
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());
}
示例11: BuildReport
private static void BuildReport()
{
string connectionString = ThemeRepositoryFactory.Default.ConnectionProvider.GetWriteConnectionString();
//获取当前报表统计表中已经统计到的日期
DateTime lastDate = new DateTime(2010, 5, 22);
string cmdText = "SELECT MAX(ReportDate) FROM VisitorsDayReport";
object result = SqlHelper.ExecuteScalar(connectionString, System.Data.CommandType.Text, cmdText);
if (result != DBNull.Value && Convert.ToInt32(result) > 0)
{
lastDate = DateTime.ParseExact(result.ToString(), "yyyyMMdd", null).AddDays(1);
}
//开始统计从上个统计日到今天的所有数据
while (lastDate < DateTime.Now.Date)
{
cmdText = string.Format(CMD_ALL_USER_COUNT, lastDate.ToString("yyyyMMdd"), lastDate.AddDays(1).ToString("yyyyMMdd"));
int allUserCount = Convert.ToInt32(SqlHelper.ExecuteScalar(connectionString, System.Data.CommandType.Text, cmdText));
cmdText = string.Format(CMD_OLD_USER_COUNT, lastDate.ToString("yyyyMMdd"), lastDate.AddDays(1).ToString("yyyyMMdd"));
int oldUserCount = Convert.ToInt32(SqlHelper.ExecuteScalar(connectionString, System.Data.CommandType.Text, cmdText));
cmdText = string.Format(CMD_INSERT_REPORT_DATA
, allUserCount
, oldUserCount
, lastDate.ToString("yyyyMMdd")
);
SqlHelper.ExecuteNonQuery(connectionString, System.Data.CommandType.Text, cmdText);
Console.WriteLine(string.Format("计算完成{0}日的统计,所有用户:{1},老用户:{2}", lastDate, allUserCount, oldUserCount));
lastDate = lastDate.AddDays(1);
}
}
示例12: CreateEvent
public static void CreateEvent(string calendarName, string id, string title, DateTime date, int status, long ownerId)
{
int calID = CalendarId(calendarName);
if (SimilarEventExists(calID, title, date))
{
// MLW TODO remove these
SMap.GetLogger().Trace("An event already exists for " + calendarName + "; Name:" + title + "; ID=" + id + "; " + date.ToString());
return;
}
else
{
SMap.GetLogger().Trace("Adding a new event for " + calendarName + "; Name:" + title + "; ID=" + id + "; " + date.ToString());
}
CalendarEvent.NameFromEventId(id);
DnDSignUpEntities entities = new DnDSignUpEntities();
Event e = new Event();
e.EventId = id;
e.Title = title;
e.AllDay = true;
e.CalendarId = calID;
e.StartTime = date;
e.EndTime = date;
e.Status = status;
e.OwnerId = ownerId;
entities.Events.Add(e);
entities.SaveChanges();
}
示例13: GenerateCalendarData
public Month GenerateCalendarData(DateTime now)
{
ViewBag.CurrentMonth = now.ToString("MMMM");
ViewBag.CurrentMonthInt = now.ToString("MM");
ViewBag.CurrentYear = now.ToString("yyyy");
ViewBag.NextMonth = new DateTime(int.Parse(ViewBag.CurrentYear), int.Parse(ViewBag.CurrentMonthInt), 1).AddMonths(1).Month;
ViewBag.PrevMonth = new DateTime(int.Parse(ViewBag.CurrentYear), int.Parse(ViewBag.CurrentMonthInt), 1).AddMonths(-1).Month;
ViewBag.NextYear = new DateTime(int.Parse(ViewBag.CurrentYear), int.Parse(ViewBag.CurrentMonthInt), 1).AddMonths(1).Year;
ViewBag.PrevYear = new DateTime(int.Parse(ViewBag.CurrentYear), int.Parse(ViewBag.CurrentMonthInt), 1).AddMonths(-1).Year;
Week week = new Week();
Month month = new Month(int.Parse(ViewBag.CurrentMonthInt), ViewBag.CurrentMonth, int.Parse(ViewBag.CurrentYear));
for (int i = 1; i <= DateTime.DaysInMonth(int.Parse(ViewBag.CurrentYear), int.Parse(ViewBag.CurrentMonthInt)); i++)
{
DateTime dt = new DateTime(int.Parse(ViewBag.CurrentYear), int.Parse(ViewBag.CurrentMonthInt), i);
Day day = new Day(dt);
day.Shifts = shiftService.GetShiftForDay(day).ToList();
week.Days.Add(day);
if (dt.DayOfWeek == DayOfWeek.Sunday || i == DateTime.DaysInMonth(int.Parse(ViewBag.CurrentYear), int.Parse(ViewBag.CurrentMonthInt)))
{
month.Weeks.Add(week);
week = new Week();
}
}
ViewBag.WeekDayCount = 0;
return month;
}
示例14: ConvertDateTime
protected static string ConvertDateTime(string dataType, DateTime value)
{
if (dataType == "DATE" || dataType == "NEWDATE")
return value.ToString("yyyy-MM-dd");
else
return value.ToString("yyyy-MM-dd HH:mm:ss");
}
示例15: DateTimeSql
private string DateTimeSql(DateTime dateTime)
{
return String.Format("'{0}'",
Column.DbType == DbType.Date
? dateTime.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)
: dateTime.ToString("yyyy-MM-dd HH:mm:ss.ffff", CultureInfo.InvariantCulture));
}