add Seconds to a date and get new date - c#

How to Get new Date provided a date and number of seconds passed from that date.For Example 03-12-2014 12:30:02 AM is the date and 124 are the seconds lapsed then new date time should be 03-12-2014 12:32:06 AM

Try something like:
string strDate = "03-12-2014 12:30:02 AM ";
DateTime date;
if (DateTime.TryParse(strDate , out date))
{
date = date.AddSeconds(124);
}

Use addition operator with a TimeSpan:
var date = myDate + TimeSpan.FromSeconds(124);

Related

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

How to split string value using c# asp.net

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

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.

Converting String (Textbox.text) to DateTime with current time

I am trying to convert this e.g. 12/31/2012 format into DateTime, however when I run this code the conversion works but the time is not current. I am looking to convert to DateTime but with the current time:
Example: When I run the below code and enter date: 12/31/2012
I get: 12/31/2012 12:00:00 AM
I am not sure how to get the current time instead of 12:00:00 AM
Console.Write("Enter Current Date: ");
string strMyDate = Console.ReadLine();
DateTime dt = DateTime.Parse(strMyDate);
Console.WriteLine(dt);
Console.ReadKey();
You can extract only the time from DateTime.Now by using the TimeOfDay property and add it to your manually entered date, e.g.
var time = dt.Add(DateTime.Now.TimeOfDay);
As an additional note, I would use DateTime.TryParse instead, as the value entered by the user may not be a parseable date, e.g.
DateTime dt;
var isDate = DateTime.TryParse(strMyDate, out dt);
if(isDate)
{
var time = dt.Add(DateTime.Now.TimeOfDay);
}
DateTime.Now will give you current time. Than combine date portion from first value with time portion from Now to get the result.
Add this to your string:
string strMyDate = Console.ReadLine();
strMyDate = string.Format("{0} {1}",
strMyDate,
DateTime.Now.ToShortTimeString());
Haven't actually compiled this but something like this should work:
DateTime dt = DateTime.Parse("12/31/2012 " + DatTime.Now.TimeOfDay.ToString());
You can build up the time from the hours, minutes and seconds portion of DateTime.Now;
string strMyDate = "12/31/2012";
DateTime dt = DateTime.Parse(strMyDate);
DateTime current = DateTime.Now;
dt = dt.AddHours(current.Hour).AddMinutes(current.Minute).AddSeconds(current.Second);
Console.WriteLine(dt);

To get time along with Date from DateTimePicker

I have a datetimepicker whose format is short.I have to get time along with date in code behind.Now 12:00:00 am is inserting along with date.Instead i need to insert current time along with date picked from datetimepicker.Can anybody help?
Create a new DateTime using the date from your input and the time from DateTime.Now.
DateTime GetDateAndCurrentTime(DateTime date)
{
return new DateTime(date.Year, date.Month, date.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
}
The actual DateTime.Value from the picker is a full DateTime object with the current time.
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
DateTime dt = dateTimePicker1.Value;
// or
string s = string.Concat(dt.ToShortDateString(), DateTime.Now.ToShortTimeString());
}
Full DateTime:
dateTimePicker1.Value;
'08/21/2011 14:42:11'
Short DateTime:
dateTimePicker1.Value.Date;
'08/21/2011 00:00:00'
The minimum value
'08/21/2011 00:00:00'
The maximum value
'08/21/2011 23:59:59'
Usage:
var firstDate = dtpFrom.Value.Date; // 0:00:00
var secondDate = dtpTo.Value.Date.AddSeconds(86400 - 1); //23:59:59 - 86400 is 24 hours
var list = Services.GetListForFilter(firstDate, secondDate);

Categories