I have various strings of type: 7/12/2012 12:02:39 AM
and would like to convert them all to just 7/12/2012 12:00:00 AM
Basically the date needs be the same, just the time must be set to 12:00:00 AM for all.
What is the best way to approach that? Except just looking for " " and replacing with 12:00:00 AM
First, parse them to a DateTime. Then you can use the Date property(0h) and parse it back to a String by using DateTime.ToString:
var oldDate = DateTime.Parse("7/12/2012 12:02:39 AM");
var usCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
var newDateStr = oldDate.Date.ToString( usCulture );
Custom Date and Time Format Strings
only just noticed that 12 AM is midnight not highnoon
You can create new DateTime instance via constuctor:
var newDate = new DateTime(oldDate.Year, oldDate.Month, oldDate.Day, 12, 0, 0);
or by adding 12 hours to the date part of the DateTime(0h):
var newDate = oldDate.Date.AddHours(12);
Parse them as DateTime
Write them back to string using yourDateTime.Date.ToString(#"G", CultureInfo.CreateSpecificCulture("en-us"))
use DateTime.Parse and specify the CulterInfo
DateTime mydat = DateTime.Parse(myString, CultureInfo.InvariantCulture);
Related
I have a string ("CompletionDate") which contains the value "2/28/2017 5:24:00 PM"
Now I have 2 variables (EDate and ETime). I want to assign the Date to EDate (i.e 2/28/2017) and Time to ETime (i.e. 5:24:00 PM).
How can I split the Date and Time from a single string.
Kindly Help.
My approach right now is like :
string CompletionDate = string.Empty;
string ProjectEDate = string.Empty;
string ProjectETime = string.Empty;
CompletionDate = "2017-03-29 12:58:00";
DateTime dt = DateTime.ParseExact(CompletionDate, "yyyy-MM-dd", CultureInfo.CreateSpecificCulture("en-us"));
DateTime dt1 = DateTime.ParseExact(CompletionDate, "HH:mm:ss", CultureInfo.CreateSpecificCulture("en-us"));
var ProjectEDate = dt.ToString();
var ProjectETime = dt1.ToString();
But its throwing exception that string is not in correct format. Kindly help
#Chris pointed one of your problems, but you have one more. You are passing full date time string and trying to treat it as date or time only, which is not true. Instead I suggest you to parse DateTime object with both date and time, and then take whatever you need from parsed object:
CultureInfo enUS = CultureInfo.CreateSpecificCulture("en-us");
DateTime dt = DateTime.ParseExact(CompletionDate, "yyyy-MM-dd HH:mm:ss", enUS);
var ProjectEDate = dt.Date.ToString();
var ProjectETime = dt.TimeOfDay.ToString();
You need to specify the full format as same as the input string to parse method.
DateTime dt = DateTime.ParseExact(CompletionDate, "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.CreateSpecificCulture("en-us"));
To get results you can use below methods available by default in DateTime.
dt.ToShortTimeString()
"12:58 PM"
dt.ToLongTimeString()
"12:58:00 PM"
dt.ToLongDateString()
"Wednesday, March 29, 2017"
dt.ToShortDateString()
"3/29/2017"
Or you can specify the format to ToString method.
dt.ToString("yyyy-MM-dd")
"2017-03-29"
dt.ToString("HH:mm:ss")
"12:58:00"
DateTime.ParseExact(CompletionDate, "yyy-MM-dd", ...
You are missing 4th 'y' in date format string:
"yyyy-MM-dd"
^
here
and:
String was not recognized as a valid DateTime " format dd/MM/yyyy"
Why do you parse into DateTime and then convert to a string using ToString again? CouldnĀ“t you just simply use String.Split when all you want is to split the time from the day and you know the exact format?
var CompletionDate = "2017-03-29 12:58:00";
var tmp = CompletionDate.Split(' ');
var ProjectEDate = tmp[0];
var ProjectETime = tmp[1];
I have a date string with dd/mm format like 06/03.Now i have to store this string into mysql table column with DATETIME format.
I am getting the problem as How can i add the current year generically because i don't want to hard code it.Subsequently how will i convert it into MySql DATETIME format for saving it.
Please help me .
You can use Parse method of DateTime:
DateTime dateTime = DateTime.Parse("06/03");
UPDATE
For your comment:
Also after parsing into DateTime i am getting date correct but time i
dont want to be 12:00:00 AM instead i want it to be 00:00:00.
12:00:00 AM corresponds to 00:00:00 only. You can verify that by getting Hour property which will return 0 and also TimeOfDay will too return 00:00:00.
Even if you try to parse exact date, it also creates the same format.
DateTime dateTime = DateTime.ParseExact("06/03 00:00:00", "dd/MM hh:mm:ss",
CultureInfo.InvariantCulture);
And you don't need conversion from DateTime object to SQL compliant DateTime object. You can pass the .Net object to SQL writer.
Consider the code:
C#
string s = "06/03";
System.DateTime dateNow = Convert.ToDateTime(s);
will give the output as you required
in VB.Net :
Dim s As String = "06/03"
Dim dateNow As Date = CDate(s)
MsgBox(dateNow)
You could do something like
var some_date = "06/03";
var year = DateTime.Now.Year;
var option = some_date+"/"+year;
Or use any of the string formats to bend it to your needs
More on date string format can be found on this MSDN page.
Edit:
If you want zeroes in the time, like your comment said, you can usit Rohit vats answer and do:
DateTime dateTime = DateTime.Parse("06/03");
var s1 = dateTime.ToString("MM/dd/yy 00:00:00");
// Output: 03/06/14 00:00:00
var s2 = dateTime.ToString("MM/dd/yyyy 00:00:00");
// Output: 03/06/2014 00:00:00
I have a string that represents a time formatted as "HH:mm", say for example "8:15" (assuming the time is in 24 hour format). In C#, How can I convert that into a DateTime instance where the date is today's date and the time is 8:15 AM?
string ds = "8:15";
string[] parts = ds.Split(new[] { ':' });
DateTime dt = new DateTime(
DateTime.Now.Year,
DateTime.Now.Month,
DateTime.Now.Day,
Convert.ToInt32(parts[0]),
Convert.ToInt32(parts[1]));
DateTime.Parse(DateTime.Now.Date.ToString() + " " + yourString);
string time ="8:15";
DateTime date = DateTime.Parse(DateTime.Now.ToString("M/d/yyyy ") + time);
Assuming situation for current date:
string time ="8:15";
var dt = Convert.ToDateTime(String.Format("{0} {1}",
DateTime.Now.ToShortDateString(),time));
If you have a valid date in string then, you can use. Also you can use DateTime.TryParse() to check for a valid date.
var date ="01/01/2014";
var dt = Convert.ToDateTime(String.Format("{0} {1}",
date,time));
You will get output
01/06/2014 08:15:00
You can probably parse the time using TimeSpan.ParseExact and then add it to today's date by
using DateTime.Add.
Given that your time is in a variable like this:
var timeText = "8:15";
Parse the time like this:
var time = TimeSpan.ParseExact(timeText, "h:mm", /*todo*/);
Fill the last argument depending on your requirements.
Then add it to today's date:
DateTime.Today.Add(time);
If I have a timestamp in the form: yyyy-mm-dd hh:mm:ss:mmm
How can I just extract the date from the timestamp?
For instance, if a timestamp reads: "2010-05-18 08:36:52:236" what is the best way to just get 2010-05-18 from it.
What I'm trying to do is isolate the date portion of the timestamp, define a custom time for it to create a new time stamp. Is there a more efficient way to define the time of the timestamp without first taking out the date, and then adding a new time?
DateTime.Parse("2010-05-18 08:36:52:236").ToString("yyyy-MM-dd");
You should use the DateTime type:
DateTime original = DateTime.Parse(str);
DateTime modified = original.Date + new TimeSpan(13, 15, 00);
string str = modified.ToString("yyyy-MM-dd HH:mm:ss:fff");
Your format is non-standard, so you'll need to call ParseExact instead of Parse:
DateTime original = DateTime.ParseExact(str, "yyyy-MM-dd HH:mm:ss:fff", CultureInfo.InvariantCulture);
You could use substring:
"2010-05-18 08:36:52:236".Substring(0, 10);
Or use ParseExact:
DateTime.ParseExact("2010-05-18 08:36:52:236",
"yyyy-MM-dd HH:mm:ss:fff",
CultureInfo.InvariantCulture)
.ToString("yyyy-MM-dd");
DateTime date;
if (DateTime.TryParse(dateString, out date))
{
date = date.Date; // Get's the date-only component.
// Do something cool.
}
else
{
// Flip out because you didn't get a real date.
}
Get the .Date member on the DateTime
DateTime date = DateTime.Now;
DateTime midnightDate = date.Date;
use it like this:
var x = DateTime.Now.Date; //will give you midnight today
x.AddDays(1).AddTicks(-1); //use these method calls to modify the date to whats needed.
The best (and fastest) way to do this is to convert the date to an integer as the time part is stored in the decimal part.
Try this:
select convert(datetime,convert(int, #yourdate))
So you convert it to an integer and then back to a data and voila, time part is gone.
Of course subtracting this result from the original value will give you the time part only.
I use this to convert DateTime value into Date and then I add 00:00:00 and 23:59:59 to make sure whole day is taken into consideration when counting stuff. I'm pretty sure it's wrong way of doing things. What would be the right way?
DateTime varObliczOd = DateTime.Parse(dateTimeWycenaPortfelaObliczDataOd.Value.ToShortDateString() + " 00:00:00");
DateTime varObliczDo = DateTime.Parse(dateTimeWycenaPortfelaObliczDataDo.Value.ToShortDateString() + " 23:59:59");
if dateTimeWycenaPortfelaObliczDataOd is of type DateTime, You can use:
dateTimeWycenaPortfelaObliczDataOd.Date
to get the date part only (time will be 00:00:00...).
If you want to get the very last tick of the date, you can use:
dateTimeWycenaPortfelaObliczDataOd.Date.AddDays(1).AddTicks(-1)
but you really better work with the next date (.AddDays(1)).
In any case, there is no need to convert to string and back to DateTime.
DateTime objects have a Date property which might be what you need.
You can use the following properties / methods on a DateTime object to get your values :
DateTime varObliczOd = dateTimeWycenaPortfelaObliczDataOd.Date;
DateTime varObliczDo = dateTimeWycenaPortfelaObliczDataOd.AddDayes(1).AddTicks(-1);
It would help to know why you're needing it, but this would work.
DateTime varObliczOd = dateTimeWycenaPortfelaObliczDataOd.Date;
DateTime varObliczDo = varObliczOd.AddDays(1).AddSeconds(-1);
Using the Date attribute and then manipulating them directly to create the required time component - no need to bother with parsing and conversion.
You could use the Date property of the DateTime object to accomplish what you need.
DateTime varObliczOd = dateTimeWycenaPortfelaObliczDataOd.Value.Date;
DateTime varObliczDo = dateTimeWycenaPortfelaObliczDataDo.Value.Date.AddDays(1);
If you really want it to end at 23:59:59 you can do:
DateTime varObliczDo = dateTimeWycenaPortfelaObliczDataDo.Value.Date.AddDays(1).AddSeconds(-1);
Will set varObliczDo to be your ending date with no time plus one day (at midnight). So if dateTimeWycenaPortfelaObliczDataDo was 2010-03-05 16:12:12 it would now be 2010-03-06 00:00:00.
Something like this maybe? I've typed this out of my head, there are probably some mistakes in the code.
DateTime varObliczOd = dateTimeWycenaPortfelaObliczDataOd.AddSeconds(-dateTimeWycenaPortfelaObliczDataOd.Seconds).AddMinutes(-dateTimeWycenaPortfelaObliczDataOd.Minutes).AddHours(-dateTimeWycenaPortfelaObliczDataOd.Hours);
DateTime varObliczDo = new DateTime(dateTimeWycenaPortfelaObliczDataDo.Year, dateTimeWycenaPortfelaObliczDataDo.Month, dateTimeWycenaPortfelaObliczDataDoDay, 23, 59, 59);
DateTime newDate = new DateTime( oldDate.Year, oldDate.Month, oldDate.Day, 23, 59,59 )
DateTime newDate = new DateTime( oldDate.Year, oldDate.Month, oldDate.Day, 0, 0, 0 )
You could work with TimeSpan:
DateTime varObliczOd = dateTimeWycenaPortfelaObliczDataOd - new TimeSpan(dateTimeWycenaPortfelaObliczDataOd.Hours, dateTimeWycenaPortfelaObliczDataOd.Minutes, dateTimeWycenaPortfelaObliczDataOd.Seconds);
Like that you avoid at least the parsing, which can fail depending on the local culture settings.