How to split string value using c# asp.net - c#

I want to split this 2015-08-11 10:59:41.830 value which is in datetime datatype format and convert it to the following format using c# asp.net.
August 11, 45 minutes ago
The given datetime(i.e-2015-08-11 10:59:41.830) will compare with the current datetime and display like the above format.Please help me to do this.

You will need to parse your date using DateTime.Parse(string s) and once you have that, you take the current date (DateTime.Now) and subtract from it the parsed date.
This should yield a TimeSpan struct. Assuming that both of the dates will refer to the same date, you can then construct your string by taking the pieces you need from the parsed date (Day and Month) and from the time span (Hours, minutes and seconds).

For your specific format you can try ParseExact() "yyyy-MM-dd HH:mm:ss.fff"
static void Main(string[] args)
{
//Given that previous and and now is the same day
DateTime previous = DateTime.ParseExact("2015-08-18 10:59:41.830", "yyyy-MM-dd HH:mm:ss.fff",
System.Globalization.CultureInfo.InvariantCulture);
DateTime now = DateTime.Now;
double value = now.Subtract(previous).TotalMinutes;
Console.WriteLine(string.Format("{0:MMMM dd}, {1} minutes ago", now, (int)value));
Console.ReadLine();
}

npinti already explained it, here the code part;
string s = "2015-08-18 10:59:41.830";
DateTime dt;
if(DateTime.TryParseExact(s, "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
var ts = dt - DateTime.Now;
Console.WriteLine("{0}, {1} minutes ago",
dt.ToString("MMMM dd", CultureInfo.InvariantCulture),
ts.Minutes);
}
I run this code 2015-08-18 09:50 in my local time and it's generate August 18, 9 minutes ago as a result.
Remember, Minutes property represents minute component of the TimeSpan object and it's range is from -59 to 59. If you wanna get all minutes based on TimeSpan object value, you can use TotalMinutes property (or even as (int)ts.TotalMinutes).

You need this
var yourString = "2015-08-11 10:59:41.830";
var oldDate = DateTime.ParseExact(yourString, "yyyy-MM-dd hh:mm:ss.fff", CultureInfo.InvariantCulture);
//The above two steps are only for if you have date in `string` type, but if you have date in `DateTime` format then skip these.
var difference = DateTime.Now - oldDate;
//here old date is parsed from string or your date in `DateTime` format
var result = string.Format("{0:MMMM dd}, {1} minutes ago", oldDate, difference.Minutes);

Related

How to convert the "time" from DateTime into int?

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;
}

Convert time string to DateTime in c#

How can I get a DateTime based on a string
e.g:
if I have mytime = "14:00"
How can I get a DateTime object with current date as the date, unless current time already 14:00:01, then the date should be the next day.
This is as simple as parsing a DateTime with an exact format.
Achievable with
var dateStr = "14:00";
var dateTime = DateTime.ParseExact(dateStr, "H:mm", null, System.Globalization.DateTimeStyles.None);
The DateTime.ParseExact() (msdn link) method simply allows you to pass the format string you wish as your parse string to return the DateTime struct. Now the Date porition of this string will be defaulted to todays date when no date part is provided.
To answer the second part
How can I get a DateTime object with current date as the date, unless
current time already 14:00:01, then the date should be the next day.
This is also simple, as we know that the DateTime.ParseExact will return todays date (as we havevnt supplied a date part) we can compare our Parsed date to DateTime.Now. If DateTime.Now is greater than our parsed date we add 1 day to our parsed date.
var dateStr = "14:00";
var now = DateTime.Now;
var dateTime = DateTime.ParseExact(dateStr, "H:mm", null, System.Globalization.DateTimeStyles.None);
if (now > dateTime)
dateTime = dateTime.AddDays(1);
You can use DateTime.TryParse(): which will convert the specified string representation of a date and time to its DateTime equivalent and returns a value that indicates whether the conversion succeeded.
string inTime="14:00";
if(DateTime.TryParse(inTime,out DateTime dTime))
{
Console.WriteLine($"DateTime : {dTime.ToString("dd-MM-yyyy HH:mm:SS")}");
}
Working example here
There is a datetime constructor for
public DateTime(
int year,
int month,
int day,
int hour,
int minute,
int second
)
So then parse the string to find the hours, minutes, and seconds and feed that into this constructor with the other parameters supplied by Datetime.Now.Day and so on.
I think you want to do something like this:
string myTime = "14:00";
var v = myTime.Split(":".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
DateTime obj = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, int.Parse(v[0]), int.Parse(v[1]), DateTime.Now.Second);

Converting Total Hours with type (double) to formatted time

I am getting total hour from this code :
string date = Request.Form[DFrom.UniqueID];
string date1 = Request.Form[DTo.UniqueID]; ;
DateTime start = DateTime.ParseExact(date, "MM/dd/yyyy hh:mm tt", null);
DateTime end = DateTime.ParseExact(date1, "MM/dd/yyyy hh:mm tt", null);
totaltime = (start - end).TotalHours;
Output will be like this :
25.44535
I want to convert the total hours to formatted time like this for example :
44:12:00
Since you have already a TimeSpan, you can format it like;
var ts = (start - end);
Console.WriteLine("{0:00}:{1:00}:{2:00}", ts.Days, ts.Hours, ts.Minutes); // 01:01:26
Remember, these Days, Hours and Minutes properties returns whole hours as an int. If you look for their fractional parts also, you can use theirs TotalXXX properties as well.
With .NET Framework 4.0, Custom TimeSpan Format Strings introduced. If you have this version or higher, you can use this custom format as well like;
Console.WriteLine("{0:dd\\:hh\\:mm}", ts);
Propably you don't want to convert this to totalHours. You can simply return a TimeSpan totaltime = (start - end)
If you would like to have in format hh:mm:ss, you can do like this:
TimeSpan ts = start- end;
string st = String.Format("{0:00}:{1:00}:{2:00}", ts.Days*24+ts.Hours, ts.Minutes, ts.Seconds);

Join date and time in c#

I have a win form c# SQL app that stores date in one column and time in the another.
There is only one date time picker on my form and I want to display both date and time values (which are from two separate columns)..
So far this is what I've done
Datetime final = datetime. Parse exact (date + " " + time , "MM/dd/yyyy hh:mm tt", cultureinfo. Invariant culture);
But it throws " string was not recognized as valid datetime" exception on the above line.
If date and time are DateTime variables, you can combine them with date arithmetic:
DateTime date=...;
DateTime time = ...;
DateTime finalDate = date.Date + time.TimeOfDay;
If they are strings, you can parse them to DateTime and TimeSpan variables:
DateTime date=DateTime.ParseExact(dateString,dateFormat,CultureInfo.InvariantCulture);
TimeSpan time = TimeSpan.ParseExact(timeString,timeFormat,CultureInfo.InvariantCulture);
DateTime finalDate = date.Date + time;
This is possible because you can add a DateTime and a TimeSpan value to get a new DateTime value
You can use TimeSpan.Parse to parse
DateTime newDateTime = date.Add(TimeSpan.Parse(time));
string d = DateTime.Now.Date.ToString("dd/MM/yyyy");
string t = DateTime.Now.ToString("h:mm");
var ts = TimeSpan.ParseExact(t, #"h\:mm",CultureInfo.InvariantCulture);
DateTime result = DateTime.ParseExact(d, "dd/MM/yyyy", CultureInfo.InvariantCulture)+ts;
Hope this helps,
Thanks.

how to convert 24-hour format TimeSpan to 12-hour format TimeSpan?

I have TimeSpan data represented as 24-hour format, such as 14:00:00, I wanna convert it to 12-hour format, 2:00 PM, I googled and found something related in stackoverflow and msdn, but didn't solve this problem, can anyone help me? Thanks in advance.
Update
Seems that it's possible to convert 24-hour format TimeSpan to String, but impossible to convert the string to 12-hour format TimeSpan :(
But I still got SO MANY good answers, thanks!
(Summing up my scattered comments in a single answer.)
First you need to understand that TimeSpan represents a time interval. This time interval is internally represented as a count of ticks an not the string 14:00:00 nor the string 2:00 PM. Only when you convert the TimeSpan to a string does it make sense to talk about the two different string representations. Switching from one representation to another does not alter or convert the tick count stored in the TimeSpan.
Writing time as 2:00 PM instead of 14:00:00 is about date/time formatting and culture. This is all handled by the DateTime class.
However, even though TimeSpan represents a time interval it is quite suitable for representing the time of day (DateTime.TimeOfDay returns a TimeSpan). So it is not unreasonable to use it for that purpose.
To perform the formatting described you need to either rely on the formatting logic of DateTime or simply create your own formatting code.
Using DateTime:
var dateTime = new DateTime(timeSpan.Ticks); // Date part is 01-01-0001
var formattedTime = dateTime.ToString("h:mm tt", CultureInfo.InvariantCulture);
The format specifiers using in ToString are documented on the Custom Date and Time Format Strings page on MSDN. It is important to specify a CultureInfo that uses the desired AM/PM designator. Otherwise the tt format specifier may be replaced by the empty string.
Using custom formatting:
var hours = timeSpan.Hours;
var minutes = timeSpan.Minutes;
var amPmDesignator = "AM";
if (hours == 0)
hours = 12;
else if (hours == 12)
amPmDesignator = "PM";
else if (hours > 12) {
hours -= 12;
amPmDesignator = "PM";
}
var formattedTime =
String.Format("{0}:{1:00} {2}", hours, minutes, amPmDesignator);
Admittedly this solution is quite a bit more complex than the first method.
TimeSpan represents a time interval not a time of day. The DateTime structure is more likely what you're looking for.
You need to convert the TimeSpan to a DateTime object first, then use whatever DateTime format you need:
var t = DateTime.Now.TimeOfDay;
Console.WriteLine(new DateTime(t.Ticks).ToString("hh:mm:ss tt"));
ToShortTimeString() would also work, but it's regional-settings dependent so it would not display correctly (or correctly, depending on how you see it) on non-US systems.
TimeSpan represents a time interval (a difference between times),
not a date or a time, so it makes little sense to define it in 24 or 12h format. I assume that you actually want a DateTime.
For example 2 PM of today:
TimeSpan ts = TimeSpan.FromHours(14);
DateTime dt = DateTime.Today.Add(ts);
Then you can format that date as you want:
String formatted = String.Format("{0:d/M/yyyy hh:mm:ss}", dt); // "12.4.1012 02:00:00" - german (de-DE)
http://msdn.microsoft.com/en-us/library/az4se3k1%28v=vs.100%29.aspx
Try This Code:
int timezone = 0;
This string gives 12-hours format
string time = DateTime.Now.AddHours(-timezone).ToString("hh:mm:ss tt");
This string gives 24-hours format
string time = DateTime.Now.AddHours(-timezone).ToString("HH:mm:ss tt");
Assuming you are staying in a 24 hour range, you can achieve what you want by subtracting the negative TimeSpan from Today's DateTime (or any date for that matter), then strip the date portion:
DateTime dt = DateTime.Today;
dt.Subtract(-TimeSpan.FromHours(14)).ToShortTimeString();
Yields:
2:00 PM
String formatted = yourDateTimeValue.ToString("hh:mm:ss tt");
It is very simple,
Let's suppose we have an object ts of TimesSpan :
TimeSpan ts = new TimeSpan();
and suppose it contains some value like 14:00:00
Now first convert this into a string and then in DateTime
as following:
TimeSpan ts = new TimeSpan(); // this is object of TimeSpan and Suppose it contains
// value 14:00:00
string tIme = ts.ToString(); // here we convert ts into String and Store in Temprary
// String variable.
DateTime TheTime = new DateTime(); // Creating the object of DateTime;
TheTime = Convert.ToDateTime(tIme); // now converting our temporary string into DateTime;
Console.WriteLine(TheTime.ToString(hh:mm:ss tt));
this will show the Result as: 02:00:00 PM
Normal Datetime can be converted in either 24 or 12 hours format.
For 24 hours format - MM/dd/yyyy HH:mm:ss tt
For 12 hours format - MM/dd/yyyy hh:mm:ss tt
There is a difference of captial and small H.
dateTimeValue.ToString(format, CultureInfo.InvariantCulture);

Categories