如何在C#中将字符串转换为日期时间为MM / dd / yyyy系统格式 [英] How to convert string to datetime for MM/dd/yyyy system format in C#
问题描述
我使用以下查询将文本文件数据上传到数据网格视图中。如果系统日期格式为dd / MM / yyyy,它的工作正常。但是,如果我将系统日期格式更改为MM / dd / yyyy,则在将文本文件上载到数据网格视图时,代码会抛出异常,因为字符串未被识别为有效日期时间。
请建议如何转换日期时间,以便成功上传文本文件。
I am using below query to upload text file data into data grid view. And Its working fine, if system date format is dd/MM/yyyy. But, if I change my system date format to MM/dd/yyyy, below code throw exception as " String was not recognized as a valid Date Time" while uploading text file into datagrid view.
Please suggest, how to convert Datetime, so that text file can be uploaded successfully.
public class User
{
public string Emp_Id { get; set; }
public DateTime Atten_Date { get; set; }
public DateTime Atten_Punch_Date { get; set; }
public string Atten_Project_code { get; set; }
public string Atten_states { get; set; }
public static List<user> LoadUserListFromFile(string location)
{
Stream mystream;
OpenFileDialog opentext = new OpenFileDialog();
if (opentext.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if ((mystream = opentext.OpenFile()) != null)
{
location = opentext.FileName;
// string filetext = File.ReadAllText(strfilename);
}
}
var users = new List<user>();
try
{
foreach (var line in File.ReadAllLines(location))
{
var columns = line.Split(new[] { '|' });
users.Add(new User
{
Emp_Id = columns[0].Trim(),
Atten_Date = Convert.ToDateTime(columns[1]),
Atten_Punch_Date = Convert.ToDateTime(columns[2]),
Atten_Project_code = columns[4].Trim(),
Atten_states = columns[3].Trim()
}
);
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Please select file to upload");
}
return users;
}
public DateTime atten { get; set; }
public DateTime atten_punch { get; set; }
}
如何在C#中将字符串转换为日期时间为MM / dd / yyyy系统格式?
How to convert string to datetime for MM/dd/yyyy system format in C#?
推荐答案
默认情况下,.NET使用en-US文化,日期为月/日/年格式。
为避免这种情况,您需要使用适当的文化。请参阅 - 字符串未被识别为有效的日期时间。 [ ^ ]有完整的解释。
By default the en-US culture is used by .NET according to which the Date is in Month/Day/Year format.
To avoid this, you need to use appropriate culture. Refer - String was not recognized as a valid DateTime.[^] for a complete explanation.
这篇关于如何在C#中将字符串转换为日期时间为MM / dd / yyyy系统格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!