convert datetime passed into parameter to a string c# - c#

I would like to convert a datetime passed into parameter into a string using this function but it doesn't work. Could anyone help me ? Thank you in advance
Here is my function
public string ConvertDateTimeToString(DateTime date)
{
string date_str = date.ToString("dd/MM/yyyy HH:mm:ss");
return date_str;
}
and after when i create a new dateTime object
DateTime dateTest = new DateTime(2008, 5, 1, 8, 30, 52);
ConvertDateTimeToString(dateTest);
Console.WriteLine(dateTest); /// show this {01/05/2008 08:30:52}

The "ConvertDateTimeToString" will create a new string.
The existing DateTime still untouched.
You have to use the new string in your Console.WriteLine :
var dateString = ConvertDateTimeToString(dateTest);
Console.WriteLine(dateString);

Related

Convert dd/mm/yyyy string to yyyy-dd-mm DateTime in c#

How do I convert 13/05/2019 (dd/mm/yyyy) string to 2019-13-05 (YYYY-dd-mm) DateTime Datatype in c#,sql sever Expects YYYY-dd-mm format datatype
string dateTime = "05/13/2019";
if (animalAdoption.AdoptionId != 0)
{
AnimalsAndBirdsAdoption animalsAndBirdsAdoption = new AnimalsAndBirdsAdoption()
{
AnimalsAndBirdsId = animalAdoption.AnimalId,
DonarDetailsId = userId,
Term = model.Term,
PeriodOfAdoption = dateTime,
isActive = true,
Amount = animalAdoption.amount
};
if (context.AnimalsAndBirdsAdoptions.Any(e => e.Id == animalAdoption.AdoptionId))
{
context.AnimalsAndBirdsAdoptions.Attach(animalsAndBirdsAdoption);
}
else
{
context.AnimalsAndBirdsAdoptions.Add(animalsAndBirdsAdoption);
}
}
this out-put I get
You can do it simply using below example with using your required format:
string dateTime = "05/13/2019";
CultureInfo provider = CultureInfo.InvariantCulture;
// It throws Argument null exception
DateTime dateTime10 = DateTime.ParseExact(dateTime, "yyyy/dd/mm", provider);
string dateTime = "13/05/2019";
var splittedDateTime = dateTime.Split('/');
DateTime myDate = new DateTime(int.Parse(splittedDateTime[2]), int.Parse(splittedDateTime[1]), int.Parse(splittedDateTime[0]));
To convert a UK date string to a DateTime
public DateTime? ToDateTime(string text)
{
DateTime? returnValue = null;
System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("en-GB");
DateTime d = new DateTime();
if(DateTime.TryParse(text, cultureInfo, System.Globalization.DateTimeStyles.None, out d))
{
returnValue = d;
}
return returnValue;
}
To convert a DateTime to string yyyy-MM-dd:
public string ToBigEndianString(DateTime? date)
{
string returnValue = null;
if(date != null)
{
returnValue = date.Value.ToString("yyyy-MM-dd");
}
return returnValue;
}
Then you can put them together:
public string ToBigEndianString(string ukDate)
{
DateTime? d = ToDateTime(ukDate);
return ToBigEndianString(d);
}
But you could pass in a DateTime to a SQL stored procedure.
https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlparametercollection.addwithvalue?view=netframework-4.8
Change the datatype of PeriodOfAdoption to Type System.DateTime
and then you can initialise the property using the DateTime constructor which has many overloads.
If your string format is always in the form yyyy-dd-mm based on: '2019-13-05'
you can extract the year the month and the day, by perhaps using .Split('-') string function or if its the format: '2019/13/05' you can split on '/' e.g. .Split('/').
Then you can create your DateTime object using the constructor like so (you can view them here https://learn.microsoft.com/en-us/dotnet/api/system.datetime.-ctor?view=netframework-4.8):
constructor:
public DateTime (int year, int month, int day);
initialisation:
PeriodOfAdoption = new DateTime(2019, 5, 13)
so putting it together:
var dateTime = '2019/13/05';
var dateParts = dateTime.Split('/');
PeriodOfAdoption = new DateTime(Int32.parse(dateParts[0]), Int32.parse(dateParts[1]), Int32.parse(dateParts[2]));
If you need a string in the c# side, this is very simple in C# and there are many examples online

Can't parse JSON data to .NET DateTime

It's pretty simple. I have a string
string s = "/Date(1474408920000)/"
And I want to convert it to a date:
DateTime date = JsonConvert.DeserializeObject<DateTime>(s);
But I get the error:
"Error parsing comment. Expected: *, got D. Path '', line 1, position 1."
What's going on here?
Thanks for your help!
Your json string is not valid but can easily be fixed by surrounding it with "
string s = #"""/Date(1474408920000)/""";
Now DateTime date = JsonConvert.DeserializeObject<DateTime>(s); will work
var LogDate = new DateTime(2016, 9, 20, 22, 2, 0, DateTimeKind.Utc);
string JsonDate = JsonConvert.SerializeObject(LogDate, new JsonSerializerSettings {
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
});
Console.WriteLine(JsonDate);
Console.ReadLine();
Output from this code gives you a proper JSON date format:
"\/Date(1474408920000)\/"
So your string should look like this:
string s = "\"\\/Date(1474408920000)\\/\"";
try serializing the DateTime obj to JSON using below code.
var dateTime = DateTime.Now;
var jsonDate = Newtonsoft.Json.JsonConvert.SerializeObject(dateTime,
new Newtonsoft.Json.JsonSerializerSettings() {
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat,
DateParseHandling = Newtonsoft.Json.DateParseHandling.DateTime });
jsonDate would hold this value "\"\\/Date(1474408920000)\\/\"" or something in this format.
Now deserialize your json date string using below code.
var dateObj = Newtonsoft.Json.JsonConvert.DeserializeObject<DateTime>(dateString,
new Newtonsoft.Json.JsonSerializerSettings() {
DateParseHandling = Newtonsoft.Json.DateParseHandling.DateTime,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat });

How convert Gregorian date to Persian date?

I want to convert a custom Gregorian date to Persian date in C#.
For example, i have a string with this contents:
string GregorianDate = "Thursday, October 24, 2013";
Now i want to have:
string PersianDate = پنج‌شنبه 2 آبان 1392 ;
or
string PersianDate = 1392/08/02
Thanks
Use the PersianCalendar:
string GregorianDate = "Thursday, October 24, 2013";
DateTime d = DateTime.Parse(GregorianDate);
PersianCalendar pc = new PersianCalendar();
Console.WriteLine(string.Format("{0}/{1}/{2}", pc.GetYear(d), pc.GetMonth(d), pc.GetDayOfMonth(d)));
DateTime date = new DateTime(2013, 10, 24);
var calendar = new PersianCalendar();
var persianDate = new DateTime(calendar.GetYear(date), calendar.GetMonth(date), calendar.GetDayOfMonth(date));
var result = persianDate.ToString("yyyy MMM ddd", CultureInfo.GetCultureInfo("fa-Ir"));
You can use PersianDateTime:
PM> Install-Package PersianDateTime
The Reference: PersianDateTime
You can use string.Split() if you need customization.
Adding up to other answers, You can get the first one by using PersianDateTime:
var gregorianDate = "Thursday, October 24, 2013";
var date = DateTime.Parse(gregorianDate);
var persianDate = new PersianDateTime(date);
var result = persianDate.ToString("dddd d MMMM yyyy");
The fowlling code should work in .net 4+ :
DateTime date=Convert.ToDateTime("2020-07-12T19:30:00.000Z");
string persianDateString = date.ToString("yyyy/MM/dd",new CultureInfo("fa-IR"));
persianDateString value would be:
1399/04/23
In windows 10, using framework 4+:
Console.WriteLine(Convert.ToDateTime("1392/08/02",new CultureInfo("fa-IR")));
or
Console.WriteLine(DateTime.Parse("1392/08/02", new CultureInfo("fa-IR")));
You can convert a DateTime to Iran time using this method:
DateTime timeInIran = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTimeToConvert, "Iran Standard Time" );

Convert string to DateTime Format - wrong format

I really cannot make sense of why this does not want to work. I get an exception:
String was not recognized as a valid DateTime.
I am reading the string date from a file and looks like this 2/27/2014 10:10:55
This method receives the filename and extrapolates the data I need (latitude, longitude, date)
public void ReadCsvFile(string filename)
{
var reader = new StreamReader(File.OpenRead(filename));
gpsDataList = new List<GpsFileClass>();
while(!reader.EndOfStream){
var line = reader.ReadLine();
var values = line.Split(',');
if(values[2].Contains("A")){
values[2] = values[2].Substring(0,values[2].IndexOf("A"));
values[2].Replace("\"", "");
values[2] = values[2].Trim();
}
if(values[2].Contains("P")){
values[2] = values[2].Substring(0, values[2].IndexOf("P"));
values[2].Replace("\"", "");
values[2] = values[2].Trim();
}
gpsDataList.Add(new GpsFileClass(Convert.ToDouble(values[0]), Convert.ToDouble(values[1]), Convert.ToString(values[2])));
}
}
Once the I have the file data in a List<> I want to do some date comparisons and calculations. But first; I try to convert the string data containing date information to datetime like this:
public void SaveFrameGpsCoordinate()
{
int listSize = gpsDataList.Count;
DateTimeFormatInfo dateTimeFormatInfo = new DateTimeFormatInfo();
dateTimeFormatInfo.ShortDatePattern = "dd-MM-yyyy HH:mm:ss";
dateTimeFormatInfo.DateSeparator = "/";
//DateTime tempDateA = DateTime.ParseExact(gpsDataList[0].timeCaptured, "dd/MM/yyyy HH:mm:ss",null);
//DateTime tempDateB = DateTime.ParseExact(gpsDataList[lastRecordData].timeCaptured, "dd/MM/yyyy HH:mm:ss", null);
DateTime tempDateA = Convert.ToDateTime(gpsDataList[0].timeCaptured.Replace("\"", ""), System.Globalization.CultureInfo.GetCultureInfo("hi-IN").DateTimeFormat);
DateTime tempDateB = Convert.ToDateTime(gpsDataList[lastRecordData].timeCaptured.Replace("\"", ""), System.Globalization.CultureInfo.GetCultureInfo("hi-IN").DateTimeFormat);
}
As you can see even ParseExact throws the same exception, I tried it (hence commented it out).
There are a lot solutions for this kind of problem but non seem to work on mine. I get that DateTime by default uses en-US calture. But When I even when I change the culture to "af-ZA" I get the same exception.
Please help.
I don't believe it; The variable that holds the size of the List<> was going out of range (check line 3 of code below) but for some reason it did not throw an "out of range exception".
public void SaveFrameGpsCoordinate()
{
int listSize = gpsDataList.Count - 1;
DateTimeFormatInfo dateTimeFormatInfo = new DateTimeFormatInfo();
dateTimeFormatInfo.ShortDatePattern = "dd-MM-yyyy HH:mm:ss";
dateTimeFormatInfo.DateSeparator = "/";
//DateTime tempDateA = DateTime.ParseExact(gpsDataList[0].timeCaptured, "dd/MM/yyyy HH:mm:ss",null);
//DateTime tempDateB = DateTime.ParseExact(gpsDataList[lastRecordData].timeCaptured, "dd/MM/yyyy HH:mm:ss", null);
DateTime tempDateA = Convert.ToDateTime(gpsDataList[0].timeCaptured.Replace("\"", ""), System.Globalization.CultureInfo.GetCultureInfo("hi-IN").DateTimeFormat);
DateTime tempDateB = Convert.ToDateTime(gpsDataList[lastRecordData].timeCaptured.Replace("\"", ""), System.Globalization.CultureInfo.GetCultureInfo("hi-IN").DateTimeFormat);
}
You can use the ParseExact method
var dateTime = DateTime.ParseExact("2/27/2014 10:10:55",
"M/d/yyyy h:m:s", CultureInfo.InvariantCulture);
'dd' expects a 2 digit date. You probably want to use 'd' instead.
Similarly 'MM' expects a 2 digit month - again you probably want to use 'M' instead.
Source: http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx

Convert comma separated string to datetime

The Exchange webservice has a method that takes the DateTime in the format below
appointment.Start = new DateTime(2014, 03, 04, 11, 30, 00);
I have a string which is formed by concatenating various fields to form the date my string is as below:
string date="2014,03,04,11,00,00"
But if i try to to parse my string as the date it gives the error "String was not recognized as a valid DateTime".
DateTime.Parse(date)
You can use DateTime.ParseExact:
string date = "2014,03,04,11,00,00";
DateTime dateTime = DateTime.ParseExact(date, "yyyy,MM,dd,HH,mm,ss", CultureInfo.CurrentCulture);
Try this :
string date = "2014,03,04,11,00,00";
DateTime datDate;
if(DateTime.TryParseExact(date, new string[] { "yyyy,MM,dd,hh,mm,ss" },
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out datDate))
{
Console.WriteLine(datDate);
}

Categories