本文整理汇总了C#中System.DateTime.GetDateTimeFormats方法的典型用法代码示例。如果您正苦于以下问题:C# DateTime.GetDateTimeFormats方法的具体用法?C# DateTime.GetDateTimeFormats怎么用?C# DateTime.GetDateTimeFormats使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.DateTime
的用法示例。
在下文中一共展示了DateTime.GetDateTimeFormats方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: runTest
public bool runTest()
{
Console.WriteLine(s_strTFPath + "\\" + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer);
String strLoc = "Loc_000oo";
String strValue = String.Empty;
int iCountErrors = 0;
int iCountTestcases = 0;
try
{
String[] ReturnValue;
Char[] InputValue = {'d', 'D', 'f', 'F', 'g', 'G', 'm', 'M', 'r', 'R', 's', 't', 'T', 'u', 'U', 'y', 'Y'};
DateTime Test = new DateTime(2000, 06, 06);
CultureInfo[] ciTest = CultureInfo.GetCultures (CultureTypes.AllCultures);
strLoc = "Loc_400vy";
foreach (CultureInfo ci in ciTest)
{
if(ci.IsNeutralCulture)
continue;
foreach (Char inputchar in InputValue)
{
iCountTestcases++;
ReturnValue = Test.GetDateTimeFormats(inputchar,ci);
if (ReturnValue.Length < 1)
{
printerr( "Error_100aa! No Date Time Formats were returned SentIn==(" + inputchar.ToString() + "," + ci.ToString() + ")" );
}
}
}
strLoc = "Loc_524vy";
iCountTestcases++;
try
{
ReturnValue = Test.GetDateTimeFormats('a',CultureInfo.InvariantCulture);
iCountErrors++;
printerr( "Error_200bb! no exception thrown");
}
catch (FormatException)
{
printinfo( "Info_512ad! Caught FormatException");
}
catch (Exception e)
{
++iCountErrors;
printerr( "Error_200aa! Wrong exception thrown: " + e.ToString());
}
} catch (Exception exc_general ) {
++iCountErrors;
Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy! strLoc=="+ strLoc +", exc_general=="+exc_general.ToString());
}
if ( iCountErrors == 0 )
{
Console.WriteLine( "paSs. "+s_strTFName+" ,iCountTestcases=="+iCountTestcases.ToString());
return true;
}
else
{
Console.WriteLine("FAiL! "+s_strTFName+" ,iCountErrors=="+iCountErrors.ToString()+" , BugNums?: "+s_strActiveBugNums );
return false;
}
}
示例2: GetAccessToken
// See Autodesk AuthTokenServer.js
// Request token from Autodesk API using credentials
private async Task<BrokerToken> GetAccessToken()
{
string baseUrl = "https://developer.api.autodesk.com/";
HttpContent reqData = new FormUrlEncodedContent(Credentials);
try
{
using (var client = new HttpClient())
{
string contentText = null;
client.BaseAddress = new Uri(baseUrl);
reqData.Headers.ContentType = new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded");
HttpResponseMessage response = await client.PostAsync("authentication/v1/authenticate", reqData);
if (!response.IsSuccessStatusCode) {
Debug.WriteLine("AUTH TOKEN: Call to AD authenticate failed.");
}
contentText = await response.Content.ReadAsStringAsync();
TokenIssuedTime = DateTime.Now;
Debug.WriteLine(contentText, "AUTH TOKEN: Content text is ");
Debug.WriteLine(TokenIssuedTime.GetDateTimeFormats('T')[0], "AUTH TOKEN: Issued time is ");
return JsonConvert.DeserializeObject<BrokerToken>(contentText);
}
}
catch (Exception exception)
{
System.Diagnostics.Debug.WriteLine("AUTH TOKEN: Caught authenticate call to AD API.");
System.Diagnostics.Debug.WriteLine(exception);
throw;
}
}
示例3: GeraUpdateComparadorProduto
public void GeraUpdateComparadorProduto()
{
DateTime data = new DateTime(2015, 11, 07);
ComparadorProdutos comparador = new ComparadorProdutos();
comparador.Id = 20;
DictionaryEntitiesAspects.GetInstance().AddOrRefreshAspect(comparador);
target = new CommandUpdateGenerator(comparador);
Assert.That(target.GetCommand(), Is.EqualTo(""));
comparador.DataComparacao = data;
comparador.ProdutoA = new Produto();
comparador.ProdutoA.Id = 4;
comparador.ProdutoA.Nome = "Trigo";
comparador.ProdutoB = new Produto();
comparador.ProdutoB.Id = 23;
comparador.ProdutoB.Nome = "Macarrão";
string update = "";
update += "UPDATE comparador_produtos ";
update += "SET data_comparacao = '" + data.GetDateTimeFormats()[54] + "', ";
update += "id_produto_a = 4, ";
update += "id_produto_b = 23 ";
update += "WHERE id = 20";
target = new CommandUpdateGenerator(comparador);
Assert.That(target.GetCommand(), Is.EqualTo(update));
}
示例4: ToString
public String ToString(List<Column> excludedColumns)
{
StringBuilder row = new StringBuilder("");
if (Values.Count > 0)
{
DateTime dateTime = new DateTime();
dateTime.GetDateTimeFormats();
for (int i = 0; i < Values.Count; i++)
{
if (!isExcludedValue(excludedColumns, Values[i]))
{
if (row.Length > 0)
row.Append(",");
if (isValidValue(Values[i].Value.ToString()))
{
if (!isDate(Values[i].Value.ToString(), out dateTime))
row.Append("'" + Values[i].Value + "'");
else
row.Append("'" + dateTime.ToString("yyyy-MM-dd") + "'");
}
else
{
row.Append("NULL");
}
}
}
}
return row.ToString();
}
示例5: GetSyncData
/// <summary>
/// Выбираем записи для синхронизации
/// </summary>
/// <param name="DT">Дата последней синхронизации</param>
public List<string> GetSyncData(DateTime DT)
{
List<string> res = new List<string>();
var dbPath = Path.Combine(ApplicationData.Current.LocalFolder.Path, dbname);
using (var db = new SQLiteConnection(dbPath))
{
string[] tm = DT.GetDateTimeFormats();
var changes = db.Query<ChangesTable>("SELECT _DBString FROM ChangesTable WHERE _ChangesDateTime >'" + tm[46] + "';");
foreach (ChangesTable ct in changes)
{
res.Add(ct._DBString);
}
}
return res;
}
示例6: ConvertToViewModel
public ReportViewModel ConvertToViewModel(IEnumerable<Record> records, double sum, DateTime date)
{
var todayDate = new DateViewModel
{
FullDate = DateTime.Now.GetDateTimeFormats()[0],
ShortDate = DateTime.Now.Month + "/" + DateTime.Now.Day + "/" + DateTime.Now.Year
};
var reportDate = new DateViewModel
{
FullDate = date.GetDateTimeFormats()[0],
ShortDate = date.Month + "/" + date.Day + "/" + date.Year
};
var recordsViewModel = new RecordsViewModel
{
Records = records.Select(ConvertToViewModel),
Sum = sum
};
return new ReportViewModel(todayDate, reportDate, recordsViewModel);
}
示例7: runTest
public bool runTest()
{
Console.WriteLine(s_strTFPath + "\\" + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer);
String strLoc = "Loc_000oo";
String strValue = String.Empty;
int iCountErrors = 0;
int iCountTestcases = 0;
try
{
String[] ReturnValue;
DateTime Test = new DateTime(2000, 06, 06);
CultureInfo[] ciTest = CultureInfo.GetCultures(CultureTypes.AllCultures);
strLoc = "Loc_400vy";
foreach (CultureInfo ci in ciTest)
{
iCountTestcases++;
if(ci.IsNeutralCulture)
continue;
ReturnValue = Test.GetDateTimeFormats(ci);
if (ReturnValue.Length < 1)
{
++iCountErrors;
printerr( "Error_100aa! No Date Time Formats were returned");
}
}
} catch (Exception exc_general ) {
++iCountErrors;
Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy! strLoc=="+ strLoc +", exc_general=="+exc_general.ToString());
}
if ( iCountErrors == 0 )
{
Console.WriteLine( "paSs. "+s_strTFName+" ,iCountTestcases=="+iCountTestcases.ToString());
return true;
}
else
{
Console.WriteLine("FAiL! "+s_strTFName+" ,iCountErrors=="+iCountErrors.ToString()+" , BugNums?: "+s_strActiveBugNums );
return false;
}
}
开发者ID:gbarnett,项目名称:shared-source-cli-2.0,代码行数:40,代码来源:co7058getdatetimeformats_iserviceobjectprovider.cs
示例8: GetDateTimeFormats_FormatSpecifier_InvalidFormat
public static void GetDateTimeFormats_FormatSpecifier_InvalidFormat()
{
var dateTime = new DateTime(2009, 7, 28, 5, 23, 15);
Assert.Throws<FormatException>(() => dateTime.GetDateTimeFormats('x')); // No such format
}
示例9: GoogleTimeFrom
//returns the Google Time Format String of a given .Net DateTime value
//Google Time Format = "2012-08-20T00:00:00+02:00"
public string GoogleTimeFrom(DateTime dt)
{
string timezone = TimeZoneInfo.Local.GetUtcOffset(dt).ToString();
if (timezone[0] != '-') timezone = '+' + timezone;
timezone = timezone.Substring(0,6);
string result = dt.GetDateTimeFormats('s')[0] + timezone;
return result;
}
示例10: UpdatePage
private void UpdatePage(DateTime date)
{
try
{
var ValuesList = new List<DateValues>();
VentsTools.currentActionString = "Подключаюсь к Базе данных";
_fndHwnd = GetCurrentThreadId();
//запустим таймер с задержкой в 1с для отображения прогрессбара (бесячий кругалек, когда все зависло)
ProgressBarPerform = new KeyValuePair<bool, int>(true, 1000);
string ventName = (string)Dispatcher.Invoke(new Func<string>(() => (VentsListBox.SelectedItem as Vents).name)); // возвращает название выбранного вентилятора
bool RDVres = _vt.ReadDayValuesFromDB(VentsConst.connectionString, VentsConst._DATAtb, ventName, date, ref ValuesList);
if (!RDVres)
throw new Exception(String.Format("Не удалось получить ежедневные данные для {0} за {1}", (string)Dispatcher.Invoke(new Func<string>(delegate { return (VentsListBox.SelectedItem as Vents).descr; })), (string)Dispatcher.Invoke(new Func<string>(delegate { return (string)dateP.DisplayDate.ToString(); }))));
//разобьем список на несколько по VentsConst._VALUE_ROWS_HOURTABLE итемов в каждом
var parts = ValuesList.DivideByLenght(VentsConst._VALUE_ROWS_DAYTABLE);
double cellWidth = (double)Dispatcher.Invoke(new Func<double>(() => workGrid.Width / VentsConst._MAXIMUM_COLUMNS_DAYTABLE));
double cellHeight = (double)Dispatcher.Invoke(new Func<double>(() => workGrid.Height / VentsConst._MAXIMUM_ROWS_DAYTABLE));
Dispatcher.Invoke(new Action(delegate { BuildDayTable(parts, cellWidth, cellHeight); })); //построим таблицу
#region autogenerated datagrid
//Dispatcher.Invoke(new Action(delegate
//{
// workGrid.Children.Clear();
// for (int i = 0; i < 3;i++ )
// {
// List<DateValues> listDV = parts[i];
// DataGrid dataGrid = new DataGrid();
// dataGrid.AutoGenerateColumns = true;
// dataGrid.MaxHeight = 380;
// //dataGrid.MaxWidth = 140;
// dataGrid.Width = 156;
// dataGrid.MaxWidth = 156;
// dataGrid.Margin = new Thickness(200 + dataGrid.Width * i, 59, 0, 0);
// dataGrid.RowHeight = 30;
// dataGrid.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
// dataGrid.VerticalAlignment = System.Windows.VerticalAlignment.Top;
// dataGrid.CanUserAddRows = false;
// dataGrid.CanUserDeleteRows = false;
// dataGrid.CanUserReorderColumns = false;
// dataGrid.CanUserResizeColumns = false;
// dataGrid.CanUserResizeRows = false;
// dataGrid.CanUserSortColumns = false;
// dataGrid.IsReadOnly = true;
// dataGrid.IsHitTestVisible = false;
// dataGrid.VerticalScrollBarVisibility = ScrollBarVisibility.Disabled;
// dataGrid.HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
// // dataGrid.HorizontalGridLinesBrush = new SolidColorBrush(Color.FromRgb(255,255,255));
// dataGrid.ItemsSource = listDV;
// dataGrid.AutoGeneratingColumn += new EventHandler<DataGridAutoGeneratingColumnEventArgs>(OnAutoGeneratingColumn);
// // var trtr = dataGrid.ColumnWidth;
// workGrid.Children.Add(dataGrid);
// }
//}));
#endregion
//calculate monthly electric power expense
int monthlyExpense = 0;
if (date != _firstMonth)
{
bool daylyRes = _vt.ReadMonthlyExpenseFromDB(VentsConst.connectionString, VentsConst._DATAtb, ventName, date, ref monthlyExpense);
if (!daylyRes)
{
throw new Exception(String.Format("Не удалось получить данные для месячного расхода {0} за {1}", (string)Dispatcher.Invoke(new Func<string>(delegate { return (VentsListBox.SelectedItem as Vents).descr; })), (string)Dispatcher.Invoke(new Func<string>(delegate { return (string)dateP.DisplayDate.ToString(); }))));
}
}
else
{
monthlyExpense = ValuesList.Last<DateValues>().value - ValuesList.First<DateValues>().value;
}
monthlyExpense = monthlyExpense * 100;
Dispatcher.Invoke(new Action(delegate { totaltb.Text = String.Format("Расход {0} за {1} равен {2} кВтч", (VentsListBox.SelectedItem as Vents).descr, date.GetDateTimeFormats('O')[0].Substring(0, 8), monthlyExpense.ToString()); }));
//generate current action string and update content of main window textbox
string descr = (string)Dispatcher.Invoke(new Func<string>(delegate { return (VentsListBox.SelectedItem as Vents).descr; }));
VentsTools.currentActionString = String.Format("Показания за {0} {1}", date.Date.GetDateTimeFormats('D', CultureInfo.CreateSpecificCulture("ru-ru"))[0], descr);
ProgressBarPerform = new KeyValuePair<bool, int>(false, 1000);
_fndHwnd = IntPtr.Zero;
}
catch (Exception ex)
{
VentsTools.currentActionString = "Не удалось подключиться к базе данных";
_log.Error(ex.Message);
ProgressBarPerform = new KeyValuePair<bool, int>(false, 1000);
_fndHwnd = IntPtr.Zero;
}
}
示例11: ChangeToDatetimeFormat
public string ChangeToDatetimeFormat(string ticks)
{
System.DateTime time = new System.DateTime(long.Parse(ticks));
string[] datetimeFormat = time.GetDateTimeFormats('f');
return datetimeFormat[0];
}
示例12: Run
public override void Run(String called)
{
called = called.ToLower();
called = called.Replace("\"", "");
called = called.Replace("o'clock", "");
List<String> words = new List<string>(called.Split(' '));
for (int i = words.Count - 1; i >= 0; --i)
{
if (_units.Keys.Contains<String>(words[i]))
continue;
words.RemoveAt(i);
}
String[] numbersString = words.ToArray();
if (numbersString.Length > 2 || numbersString.Length == 0)
{
Speak("I don't understand that time " + String.Join(" ", numbersString));
return;
}
int year = DateTime.Today.Year;
int month = DateTime.Today.Month;
int day = DateTime.Today.Day;
int hour = _units[numbersString[0]];
int minute = numbersString.Length == 2 ? _units[numbersString[1]] : 0;
DateTime wakeupTime = new DateTime(year, month, day, hour, minute, 0);
DateTime old = wakeupTime;
if (wakeupTime < DateTime.Now)
{
wakeupTime = wakeupTime.AddHours(12);
if (wakeupTime < DateTime.Now)
{
wakeupTime = old.AddDays(1);
}
}
SetWaitForWakeUpTime(wakeupTime);
_wakeUpTimer = new Timer();
_wakeUpTimer.Interval = (int)(wakeupTime - DateTime.Now).TotalMilliseconds;
_wakeUpTimer.AutoReset = false;
_wakeUpTimer.Elapsed += new ElapsedEventHandler(_wakeUpTimer_Elapsed);
_wakeUpTimer.Start();
Speak("Wake up set for " + wakeupTime.GetDateTimeFormats()[110]);
WakeUpSet = true;
Settings.Muted = true;
}
示例13: RolloverFile
/// <summary>
/// Performs file rollover by renaming the current log file and deleting old files as necessary.
/// The rename causes the next log request to generate a new file and log to it.
/// </summary>
/// <param name="logFile">Base log file name.</param>
/// <param name="createdDate">The date the file to be renamed was initially created.</param>
/// <param name="rollOverFilesToKeep">Number of files to keep. Causes deletion of oldest files.</param>
/// <returns>True if successful.</returns>
private bool RolloverFile(string logFile, DateTime createdDate, int rollOverFilesToKeep)
{
string stringDate = createdDate.GetDateTimeFormats()[103]; //Get the date in a format to use in the file name.
stringDate = stringDate.Replace(":", ".");
string stringTicks = DateTime.Now.Ticks.ToString();
string directoryName = Path.GetDirectoryName(logFile);
string rolledLogFile = "";
bool success = false;
try
{ //Rename the file with date and time plus ticks to ensure uniqueness
rolledLogFile = Path.Combine(directoryName, Path.GetFileNameWithoutExtension(logFile) + "_" + stringDate + "." + stringTicks + Path.GetExtension(logFile));
File.Move(logFile, rolledLogFile); //Rename the file with a date.
string[] archivedFiles = Directory.GetFiles(directoryName, Path.GetFileNameWithoutExtension(logFile) + "_*" + Path.GetExtension(logFile));
if (archivedFiles.Length > (rollOverFilesToKeep))
{
Array.Sort(archivedFiles);
for (int i=0; i < (archivedFiles.Length - rollOverFilesToKeep); i++)
{
File.Delete(Path.Combine(directoryName, archivedFiles[i]));
}
}
success = true;
}
catch (Exception e)
{ //Default to continue logging rather than raising an error.
//If the file was already moved or other error, we're assuming another process succeeded.
Logger.Write("Failed rolling over or deleting files: " + logFile + Environment.NewLine + e.Message);
}
return success;
}
示例14: IsAddDayFun
private int IsAddDayFun(DateTime dt, DateTime isAddDay, int days, bool schedule)
{
long num_date = CommonFunction.GetPHPTime(dt.ToString());///獲得基本發貨時間的基數
string dtFlagStr = isAddDay.GetDateTimeFormats()[0] + " 15:00";///計算出是否+1天的時間邊
long dtFlag = CommonFunction.GetPHPTime(dtFlagStr);///獲得當天15:00的時間蹉
long isAddDayInt = CommonFunction.GetPHPTime(isAddDay.ToString("yyyy-MM-dd HH:mm:ss"));///獲得下單時間的時間戳
DateTime dateBase = dt.Date;///獲得預計出貨日的日期部份
DateTime dateDay = isAddDay.Date;///獲得下單日期的日期部份
if (dateBase != dateDay && schedule==true)
{
return days;
}
else
{
return days = (isAddDayInt - dtFlag) > 0 ? days + 1 : days; //判斷時間是否大於15點,大於時,運達天數加1
}
}
示例15: TestGetDateTimeFormats
public static void TestGetDateTimeFormats()
{
char[] allStandardFormats =
{
'd', 'D', 'f', 'F', 'g', 'G',
'm', 'M', 'o', 'O', 'r', 'R',
's', 't', 'T', 'u', 'U', 'y', 'Y',
};
DateTime july28 = new DateTime(2009, 7, 28, 5, 23, 15);
List<string> july28Formats = new List<string>();
foreach (char format in allStandardFormats)
{
string[] dates = july28.GetDateTimeFormats(format);
Assert.True(dates.Length > 0);
DateTime parsedDate;
Assert.True(DateTime.TryParseExact(dates[0], format.ToString(), CultureInfo.CurrentCulture, DateTimeStyles.None, out parsedDate));
july28Formats.AddRange(dates);
}
List<string> actualJuly28Formats = july28.GetDateTimeFormats().ToList();
Assert.Equal(july28Formats.OrderBy(t => t), actualJuly28Formats.OrderBy(t => t));
actualJuly28Formats = july28.GetDateTimeFormats(CultureInfo.CurrentCulture).ToList();
Assert.Equal(july28Formats.OrderBy(t => t), actualJuly28Formats.OrderBy(t => t));
}