Convert string value to date from FormCollection - c#

I get new Date(2012,9,3) from FormCollection["eventDate"]
how can I get this value in DateTime variable?

string input = "new Date(2012,9,3)";
var dateTimeString = input.Split(new[] {'(', ')'},
StringSplitOptions.RemoveEmptyEntries)
.Last();
var datetime = DateTime.ParseExact(dateTimeString,
"yyyy,M,d", CultureInfo.InvariantCulture);

One way would be like this:
// new Date(2012,9,3)
var dateVals = s.Substring(9).Replace(")", "").Split(",");
var d = new DateTime(
Convert.ToInt32(dateVals[0]),
Convert.ToInt32(dateVals[2]),
Convert.ToInt32(dateVals[1]));

Related

C# How to DateTimeOffset.Parse 2022003023T05:57:44.200Z?

I tried DateTimeOffset dto = DateTime.ParseExact("2022003023T05:57:44.200Z", "yyyyMMMMdd'T'HH':'mm':'ss'.'fff'Z'", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal); but to no avail: 'String '2022003023T05:57:44.200Z' was not recognized as a valid DateTime.'
(Would be a mess as a comment)
If those extra 0's were typos for separators (2022/03/23T05:57:44.200Z being the real value), then:
void Main()
{
string s = "2022003023T05:57:44.200Z";
var ss = s.ToCharArray();
ss[4] = '/';
ss[7] = '/';
var dt = new string(ss);
DateTimeOffset dto = DateTime.Parse(dt);
Console.WriteLine(dto);
}

How to parse a string with many dates into a List<DateTme>?

I have a string that look like this:
[12-20-2019 11:27:57, 12-20-2019 11:27:58, 12-20-2019 11:27:59] each date is separate by , how can I parse it into a List<DateTime>?
My code is:
string datesListString = JObject.Parse(jsonContent)["datesList"].ToString();
ListDateTime> datesList = new JavaScriptSerializer().Deserialize<List<DateTime>>(datesListString);
DatesListString is a field of a big JSON file that I need to deserialize.
string yourString = "[12-20-2019 11:27:57, 12-20-2019 11:27:58, 12-20-2019 11:27:59]";
List<DateTime> dates = yourstring
.Trim('[', ']')
.Split(new[] { ", " }, StringSplitOptions.None)
.Select(s => DateTime.ParseExact(s, "MM-dd-yyyy hh:mm:ss", null))
.ToList();
You can do it by combining string.Split method and Select from System.Linq
var dateString = "12-20-2019 11:27:57, 12-20-2019 11:27:58, 12-20-2019 11:27:59";
var result = dateString.Split(',').Select(d => DateTime.Parse(d, CultureInfo.InvariantCulture));
To skip the square braces you can simply use Trim method, like that
var dateString = "[12-20-2019 11:27:57, 12-20-2019 11:27:58, 12-20-2019 11:27:59]".Trim('[', ']');
You can simply try:
string dateTimes = "12-20-2019 11:27:57, 12-20-2019 11:27:58, 12-20-2019 11:27:59";
string[] splitDateTime = dateTimes.Split(',');
List<DateTime> dates = new List<DateTime>();
foreach (string dateTime in splitDateTime)
{
DateTime date;
if (DateTime.TryParseExact(dateTime, "MM-dd-yyyy hh:mm:ss",
CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
dates.Add(date);
}
You need to split the string first, and then you can use DateTime.Parse(str) to get the DateTime object.
This demonstrates it:
using System;
public class Program
{
public static void Main()
{
string str = "[12-20-2019 11:27:57, 12-20-2019 11:27:58, 12-20-2019 11:27:59]";
str = str.Substring(1, str.Length - 2);
string[] parts = str.Split(',');
foreach(var part in parts) {
str = str.Trim();
var date = DateTime.Parse(part);
Console.WriteLine(date);
}
}
}
It looks like it is JSON:
var _str = #"[""12-20-2019 11:27:57"", ""12-20-2019 11:27:58"", ""12-20-2019 11:27:59""]";
So we can use using Newtonsoft.Json;:
using Newtonsoft.Json;
var list = JsonConvert.DeserializeObject<List<string>>(_str)
.Select(s => DateTime.Parse(s, CultureInfo.InvariantCulture));
Read mode about library Json.NET

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 to display date only from datetime type into datetime object

In string array I have date field, which I want to format for date only and bind it to date time object.
string[] strArray = new string[] {
"Mahesh Chand",
"Mike Gold",
"Raj Beniwal",
"Praveen Kumar",
"7/10/1974 7:10:24 AM"
};
DateTime dateFromString = Convert.ToDateTime(strArray[4]);
DateTime dt = DateTime.ParseExact(dateTimeString, "dd/MM/yyyy", null);
Am not getting only date. still am getting date and time.
You can take only the Date without Time from a DateTime object in this way:
DateTime dateFromString = Convert.ToDateTime(strArray[4]);
var onlyDate = dateFromString.Date;
// Display date using short date string.
Console.WriteLine(onlyDate .ToString("d"));
More info on MSDN
Use like this
string[] strArray = new string[] {
"Mahesh Chand",
"Mike Gold",
"Raj Beniwal",
"Praveen Kumar",
"7/10/1974 7:10:24 AM" };
DateTime dateFromString = Convert.ToDateTime(strArray[4]);
string dt= DateTime.ParseExact(dateTimeString, "dd/MM/yyyy", null).ToString("dd/MM/yyyy");
in this way you will get date as string, but if you want only date part as DateTime type then it isn't possible because in DateTime type if you don't specify any time then it will automatically add a default time as 12:00:00 AM(00:00:00) in DateTime
Update
you can use like this for all culture
string dt = DateTime.ParseExact(dateTimeString, "dd/MM/yyyy", CultureInfo.InvariantCulture)
.ToString("dd/MM/yyyy");
or you can use simply like this
string[] strArray = new string[] {
"Mahesh Chand",
"Mike Gold",
"Raj Beniwal",
"Praveen Kumar",
"7/10/1974 7:10:24 AM" };
string dateFromString = Convert.ToDateTime(strArray[4]).ToString("dd/MM/yyyy");

Retrieve DateTime objects from a certain string

I have the following string:
"23/09/2015 08:00\r\n עד\r\n24/09/2015 08:00"
As you can see, we have two dates. One before the first \r\n and the other one after the second \r\n.
How can I retrieve DateTime objects from this string in C#? The only way I know is to use Substring but that retrieves the text after the first \r\n.
This may help
var stringValue = "23/09/2015 08:00\r\n עד\r\n24/09/2015 08:00";
var splitted = stringValue.Split(new string[]{"\r\n"},StringSplitOptions.RemoveEmptyEntries);
var firstStringDate = splitted[0];
var secondStringDate = splitted[2];
And to get the DateTime:
var firstDate = DateTime.ParseExact(splitted[0], "dd/MM/yyyy HH:mm", DateTimeFormatInfo.InvariantInfo);
var secondDate = DateTime.ParseExact(splitted[2], "dd/MM/yyyy HH:mm", DateTimeFormatInfo.InvariantInfo);
Split and TryParse the strings:
static IEnumerable<DateTime> extractDates(string inputString)
{
foreach (var item in inputString.Split(new string[] {"\r\n"}, StringSplitOptions.RemoveEmptyEntries))
{
DateTime dt;
if(DateTime.TryParseExact(item,
"dd/MM/yyyy HH:mm",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out dt))
yield return dt;
}
}
I would use myString.Split("\r\n") like so:
string[] dates = myString.Split("\r\n");
foreach (var dateString in dates)
{
DateTime dateTime;
if (DateTime.TryParse(dateString, out dateTime))
{
//Use dateTime here
}
}

Categories