Given two strings with the following values:
31/05/2013 0:00:00
21:22
What's the most efficient way to join them into a DateTime data type to get:
31/05/2013 21:22
The time portion of the first string "0:00:00" is ignored, in favor of using the "time" from the second string.
Use a TimeSpan object and DateTime.Add(yourTimeSpan); e.g.
DateTime dt = new DateTime(2013,05,31);
var dts = dt.Add(new TimeSpan(0, 21, 22, 0, 0));
Extending the answer a bit, you can parse the date and time first, e.g.
DateTime dt = DateTime.Parse("05/31/2013 0:00:00");
TimeSpan ts = TimeSpan.Parse("21:22");
var dts = dt.Add(ts);
...keep in mind, I am not checking for bad date/time values. If you're unsure if the values are real dates/times, use DateTime.TryParse and handle appropriately.
As #George said, parse the first value as a DateTime and then another one as TimeSpan and then add the TimeSpan to first parsed value.
Another option is getting the substring of first 10 charachters of first value and concat it with a space with second value and parse it as DateTime.
Say that the first string is called one and the second one is called two, just do this:
DateTime result = DateTime.Parse(one).Date + DateTime.Parse(two).TimeOfDay;
string strDate = "31/05/2013 0:00";
string strTime = "21:22";
strDate = strDate.Replace("0:00", strTime);
DateTime date = Convert.ToDateTime(strDate);
If you are really dealing with only strings, then:
string strDate = "31/05/2013 0:00:00";
string strTime = "21:22";
string strDateTime = strDate.Split(' ')[0] + " " + strTime;
If you can safely assume you are getting 2 digit month and day, a 4 digit year, and a space after the date:
var date = "31/05/2013 0:00:00";
var time = "21:22";
var dateTime = DateTime.Parse(date.Substring(0,11) + time);
If the assumptions about the input format aren't solid you could use a regex to extract the date instead of Substring.
If you're starting out with just strings, you can just do this:
var dateString = "31/05/2013 00:00";
var timeString = "21:22";
var dateTimeString = dateString.Substring(0, 11) + timeString;
var output = DateTime.ParseExact(dateTimeString, "dd/MM/yyyy HH:mm", null);
Assuming you know for sure this format won't change (a dangerous assumption, to be sure), this will work. Otherwise, you'd have to parse the date and time strings separately and use conventional date manipulation as others suggested. For example:
var ci = System.Globalization.CultureInfo.CreateSpecificCulture("en-GB");
var dateString = "31/05/2013 00:00";
var timeString = "21:22";
var output = DateTime.Parse(dateString, ci) + TimeSpan.Parse(timeString, ci);
DateTime date = DateTime.ParseExact("31/05/2013 0:00:00", "dd/MM/yyyy h:mm:ss", CultureInfo.InvariantCulture);
TimeSpan span = TimeSpan.ParseExact("21:22", "t", CultureInfo.InvariantCulture);
DateTime result = date + span;
Related
I have string data that comes in the following sequence:
"4:32", "1:08"
I want to convert this to 24hr time
where "4:32" becomes 16:32
Parse that to a TimeSpan, then add 12 hours:
var offset = TimeSpan.FromHours(12);
var time = TimeSpan.Parse("4:32").Add(offset);
Parse the input string to a TimeSpan, add 12 hours, then format the TimeSpan with the desired string format:
string input = "4:32";
string output = TimeSpan.Parse(input).Add(TimeSpan.FromHours(12)).ToString("hh\\:mm");
// output: "16:32"
As per your comment, once you know if the hour is AM/PM, you could parse the value with it's suffix and then use the HH custom format specifier:
DateTime d = DateTime.Parse("4:32 PM");
Console.WriteLine(d.ToString("HH:mm"));
to convert it to 24h format.
https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings#HH_Specifier
In the simple case your question suggests, where you know beforehand that the string is 12-hour in the format h:mm and it refers to PM, never AM, then you can split the string, parse the hour, add 12, and reassemble it.
var inputString = "4:32";
var splits = inputString.Split(':');
var hourString = splits[0];
var minuteString = splits[1];
var hour = int.Parse(hourString);
hour = hour + 12;
var outputString = $"{hour}:{minuteString}";
If you're doing anything more complicated with dates or times, you probably want to use DateTime or similar classes.
I have a DataGrid which contains a few values that are in hours and I wanted to know:
How to get ONLY the time from my DataGrid and convert it into an int (or double) variable.
My goal is to do a few operations with my DataGrid time values, like to add numbers into it
EXAMPLE:
Using my "dataGridView1.Rows[1].Cells[2].Value.ToString();" It'll show a DateTime value (which is inside my DataGrid), with this value, I wanna filter ONLY the time from this and convert it into an int
the part of my code which I wanna "capture" the time:
txtAtiv.Text = dataGridView1.Rows[0].Cells[1].Value.ToString();
string value = dataGridView1.Rows[0].Cells[2].Value.ToString();
lblLeft.Text = value.Split(' ')[1];
I wanna get the "value" (which is a DateTime value from the DataGrid) and convert it into an int.
note:
- The date for me in my dataGrid it's not relevant, I only have to pick the time (and yes, I know that I can't "split" DateTime to do them separately)
If you are willing to be limited to millisecond resolution, then this is fairly easy.
Given a date/time that you want to get the time part from as an int, you can get the number of milliseconds since midnight, like so:
DateTime dateTime = DateTime.Now;
int timeMsSinceMidnight = (int)dateTime.TimeOfDay.TotalMilliseconds;
If you want to reconstitute the original date and time from this, you need the original date and the time since midnight in milliseconds:
DateTime date = dateTime.Date; // Midnight.
DateTime restoredTime = date.AddMilliseconds(timeMsSinceMidnight);
Test program:
DateTime dateTime = DateTime.Now;
Console.WriteLine("Original date/time: " + dateTime );
int timeMsSinceMidnight = (int)dateTime.TimeOfDay.TotalMilliseconds;
DateTime date = dateTime.Date; // Midnight.
DateTime restoredTime = date.AddMilliseconds(timeMsSinceMidnight);
Console.WriteLine("Restored date/time: " + restoredTime);
The value returned from time.TimeOfDay is of type TimeSpan, which is convenient for storing time-of-day values.
If you want to turn your "milliseconds since midnight" back into a TimeSpan, you just do this:
var timeSpan = TimeSpan.FromMilliseconds(timeMsSinceMidnight);
First step is to convert string to DateTime. Use DateTime.TryParse(string value, out DateTime dt). Then as Mathew Watson rightly suggested, get the value of variable dt converted to milliseconds using dt.TimeOfDay.TotalMilliseconds. It is also possible to convert the span in TotalSeconds or TotalMinutes if it suits your requirement.
Try to avoid calling ToString() method directly before checking if cell value is null. If I want to avoid the check, I would make compiler to do it by using something like : Rows[3].Cells[2].Value + "" instead of Value.ToString().
Mixing Mathew's and Mukesh Adhvaryu's answers, I got into this one, and it fits perfectly on what I need, thank you guys for your support!
txtAtiv.Text = dataGridView1.Rows[0].Cells[1].Value + "";
string value = dataGridView1.Rows[0].Cells[2].Value + "";
lblLeft.Text = value.Split(' ')[1];
textStatus.Text = "";
DateTime timeConvert;
DateTime.TryParse(value, out timeConvert);
double time;
time = timeConvert.TimeOfDay.TotalMilliseconds;
var timeSpan = TimeSpan.FromMilliseconds(time);
lblSoma.Text = timeSpan.ToString();
static void Main(string[] args)
{
string time1 = "11:15 AM";
string time2 = "11:15 PM";
var t1 = ConvertTimeToInt(time1);
var t2 = ConvertTimeToInt(time2);
Console.WriteLine("{0}", t1);
Console.WriteLine("{0}", t2);
Console.WriteLine("{0:dd/MM/yyyy hh:mm tt}", ConvertIntToTime(t1));
Console.WriteLine("{0:dd/MM/yyyy hh:mm tt}", ConvertIntToTime(t2));
Console.ReadLine();
}
static long ConvertTimeToInt(string input)
{
var date = DateTime.ParseExact(input, "hh:mm tt", CultureInfo.InvariantCulture);
TimeSpan span = date.TimeOfDay;
Console.WriteLine("{0:dd/MM/yyyy hh:mm tt}", date);
return span.Ticks;
}
static DateTime ConvertIntToTime(long input)
{
TimeSpan span = TimeSpan.FromTicks(input);
var date = new DateTime(span.Ticks);
Console.WriteLine("{0:dd/MM/yyyy hh:mm tt}", date);
return date;
}
I have a requirement regarding the parsing of date strings of the form "dd/MM/yy" such that if the year is deemed greater than 30 years from the current year then it would prefix the year with 19. In the other instance it is prefixed with 20.
Examples:
01/01/50 -> 01/01/1950
01/01/41 -> 01/01/2041
I'm not sure how DateTime.ParseExact decides what prefix it should use or how I can force it one way or the other (it does appear to make a sane assumption as 01/01/12 -> 01/01/2012, I just don't know how to dictate the point at which it will switch).
Use the Calendar.TwoDigitYearMax property.
Gets or sets the last year of a 100-year range that can be represented
by a 2-digit year.
In your case, something like this would work:
// Setup
var cultureInfo = (CultureInfo)Thread.CurrentThread.CurrentCulture.Clone();
var calendar = cultureInfo.Calendar;
calendar.TwoDigitYearMax = DateTime.Now.Year + 30;
cultureInfo.DateTimeFormat.Calendar = calendar;
// Parse
var _1950 = DateTime.ParseExact("01/01/50", "dd/MM/yy", cultureInfo);
var _2041 = DateTime.ParseExact("01/01/41", "dd/MM/yy", cultureInfo);
I do not think that ParseExact can do your job, so here my version with conditional blocks but works.
Try This:
DateTime currentDate = DateTime.Now;
String strDate = "01/01/41";
DateTime userDate=DateTime.ParseExact(strDate, "dd/MM/yy", System.Globalization.CultureInfo.InvariantCulture);
currentDate=currentDate.AddYears(30);
if ((userDate.Year%100) > (currentDate.Year%100))
{
strDate = strDate.Insert(6, "19");
}
else
{
strDate = strDate.Insert(6, "20");
}
DateTime newUserDate = DateTime.ParseExact(strDate, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
Given two strings
string date = "02Mar13";
string duration = "03.20min";
How do I parse them to DateTime and show them in the following format
string date = "02 March 2013";
string duration = "00:03:20";
I went through the list here but no one match my requirements.
You need to parse these using a Custom Date and Time format string, and output using one as well:
DateTime dt = DateTime.ParseExact(date + duration,
"ddMMMyymm.ss'min'",
CultureInfo.InvariantCulture);
string newDate = dt.ToString("dd MMMM yyyy");
string newDuration = dt.ToString("HH:mm:ss");
Things to note: I am using 'min' to represent the min literal in the string - this is part of custom format strings, allowing inner string literals.
string date = "02Mar13";
string duration = "03.20min";
DateTime newDate = DateTime.ParseExact(date + duration, "ddMMMyymm.ss\\min", null);
date = newDate.ToString("dd MMMM yyyy");
duration = newDate.ToString("hh:mm:ss");
How can produce the dateResult
string date = "02Mar13";
string duration = "03.20min";
var mat=Regex.Match(duration, "(.+?)min");
var dateResult = DateTime.ParseExact(date + mat.Groups[1].Value.Replace(".",":"), "ddMMMyyHH:mm", Thread.CurrentThread.CurrentCulture);
DateTime parsing is pretty much straightforward using DateTime.ParseExact:
DateTime.ParseExact(date, "ddMMMyy", null).ToString("dd MMMM yyyy"); // "02 March 2013"
As for the second part, if it is a duration semantically, then it is more suitable to use TimeSpan.ParseExact (although it required some fiddling with format strings):
TimeSpan.ParseExact(duration, "mm\\.ss'min'", null).ToString("hh\\:mm\\:ss"); // "00:03:20"
How to convert date format to DD-MM-YYYY in C#? I am only looking for DD-MM-YYYY format not anything else.
string formatted = date.ToString("dd-MM-yyyy");
will do it.
Here is a good reference for different formats.
According to one of the first Google search hits:
http://www.csharp-examples.net/string-format-datetime/
// Where 'dt' is the DateTime object...
String.Format("{0:dd-MM-yyyy}", dt);
Here is the Simplest Method.
This is the String value: "5/13/2012"
DateTime _date;
string day = "";
_date = DateTime.Parse("5/13/2012");
day = _date.ToString("dd-MMM-yyyy");
It will output as: 13-May-2012
string formattedDate = yourDate.ToString("dd-MM-yyyy");
DateTime dt = DateTime.Now;
String.Format("{0:dd-MM-yyyy}", dt);
DateTime s1 = System.Convert.ToDateTime(textbox.Trim());
DateTime date = (s1);
String frmdt = date.ToString("dd-MM-yyyy");
will work
DateTime dt = DateTime.Now;
String.Format("{0:dd-MM-yyyy}", dt);
First convert your string into DateTime variable:
DateTime date = DateTime.Parse(your variable);
Then convert this variable back to string in correct format:
String dateInString = date.ToString("dd-MM-yyyy");
Here we go:
DateTime time = DateTime.Now;
Console.WriteLine(time.Day + "-" + time.Month + "-" + time.Year);
WORKS! :)
From C# 6.0 onwards (Visual Studio 2015 and newer), you can simply use an interpolated string with formatting:
var date = new DateTime(2017, 8, 3);
var formattedDate = $"{date:dd-MM-yyyy}";
Do you have your date variable stored as a String or a Date type?
In which case you will need to do something like
DateTime myDate = null;
DateTime.TryParse(myString,myDate);
or
Convert.ToDateTime(myString);
You can then call ToString("dd-MM-yyyy") on your date variable
I ran into the same issue. What I needed to do was add a reference at the top of the class and change the CultureInfo of the thread that is currently executing.
using System.Threading;
string cultureName = "fr-CA";
Thread.CurrentThread.CurrentCulture = new CultureInfo(cultureName);
DateTime theDate = new DateTime(2015, 11, 06);
theDate.ToString("g");
Console.WriteLine(theDate);
All you have to do is change the culture name, for example:
"en-US" = United States
"fr-FR" = French-speaking France
"fr-CA" = French-speaking Canada
etc...
The problem is that you're trying to convert a string, so first you should cast your variable to date and after that apply something like
string date = variableConvertedToDate.ToString("dd-MM-yyyy")
or
string date = variableConvertedToDate.ToShortDateString() in this case result is dd/MM/yyyy.
dateString = "not a date";
// Exception: The string was not recognized as a valid DateTime. There is an unknown word starting at index 0.
DateTime dateTime11; // 1/1/0001 12:00:00 AM
bool isSuccess2 = DateTime.TryParseExact(dateString, "MM/dd/yyyy", provider, DateTimeStyles.None, out dateTime11);
var dateTimeString = "21-10-2014 15:40:30";
dateTimeString = Regex.Replace(dateTimeString, #"[^\u0000-\u007F]", string.Empty);
var inputFormat = "dd-MM-yyyy HH:mm:ss";
var outputFormat = "yyyy-MM-dd HH:mm:ss";
var dateTime = DateTime.ParseExact(dateTimeString, inputFormat, CultureInfo.InvariantCulture);
var output = dateTime.ToString(outputFormat);
Console.WriteLine(output);
Try this, it works for me.
you could do like this:
return inObj == DBNull.Value ? "" : (Convert.ToDateTime(inObj)).ToString("MM/dd/yyyy").ToString();