在C#中将字符串/数字转换为可排序的dateTime(反之) [英] Convert string/number to sortable dateTime in C# (and the reverse)
问题描述
我正在开发一个跟踪学生出勤率的类似信息的应用程序,并简化日期输入的注册。我已经将YYYYMMDD写入输入日期,(例如:20140429 - 没有任何标点符号,因为它易于处理并且在排序方面具有优势)。但是,机器不知道这是一个日期,所以选择使用datepicker似乎很难。
我想将日期存储为数据库中的数字,(在这种情况下,我可能会使用SQLite,访问或CSV文件和简单的可排序日期/数字)。我做了一些谷歌,但我真的不知道从哪里开始;我应该使用字符串操作吗?在.net中的DateTime中是否有一些我缺少的功能?
任何帮助都将不胜感激!
-Frank
I am working on an application to track student attendance an similar information, and to simplify the registration of the typing of dates. I've gone with writing YYYYMMDD to input dates, (ex: 20140429 - without any punctuation marks, as it's simple to handle and has it's advantages in terms of sorting). However, the machine don't know this is a date and so having the option to using a "datepicker" seems difficult.
I want to store the date as a number in the database, (I might use a SQLite, access or CSV -file and a simple sortable date/number is great in this situation). I have done some Google-ing, but I don't really know where to start; should I use "string manipulation"? Are there some functionality in the DateTime in .net that I am missing?
Any help would be appreciated!
-Frank
推荐答案
您可以使用DateTime.TryParseExact
方法将输入文本转换为日期时间
you can useDateTime.TryParseExact
method to convert your input text to date time
string str = "20140429";
string[] format = {"yyyyMMdd"};
DateTime date;
if (DateTime.TryParseExact(str,
format,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out date))
{
//valid and insert in to database as DateTime value
}
DateTime.TryParseExact
如果您的输入字符串格式正确,则返回true。不要将日期时间保存为数据库中的整数或文本字段。将其保存为Date或DateTime。
DateTime.TryParseExact
method return true if your input string in correct format. don't save your date time as integer or text field in database. Save it as Date or DateTime.
我使用了DamithSL的解决方案,并进行了调整(我保留了小型控制台应用程序以供参考),并添加了一种将值返回给字符串的方法。
希望这对其他人有用:- $
I used DamithSL's solution, with a tweak, (I keep small console applications laying around for reference), and added a way to return the value to a string.
Hope this can be useful to someone else :-D
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ParseDateTimeYYYYMMDDconsole
{
class Program
{
static void Main(string[] args)
{
string str = "20140429";
string[] format = { "yyyyMMdd" };
DateTime date;
string ReStringed;
if (DateTime.TryParseExact(str,
format,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out date))
{
Console.WriteLine("The raw string of YYYYMMDD date:");
Console.WriteLine(str);
Console.WriteLine("Date given after conversion to DateTime:");
Console.WriteLine(date);
ReStringed = date.ToString("yyyyMMdd");
Console.WriteLine("The date re-converted
back to a string, formatted yyyyMMdd:");
Console.WriteLine(ReStringed);
Console.ReadLine();
}
}
}
}
这篇关于在C#中将字符串/数字转换为可排序的dateTime(反之)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!