I have a dropdownlist that displays time. For example 8:00AM or 8:30AM.
When I save this time to database, I want to save as todays date + time.
eg: 8:00AM as 03/30/2009 8:00:00:000. Can anybody give appropriate code to convert as shown above?
I tried
Convert.ToDateTime(ddlStartTime.SelectedItem.Text)
But there is an error stating "String was not recognized as a valid DateTime."
VB.NET answer for Portmans Solution. Too many chars for comment so included here.
Dim time As String() = Me.DropDownList1.SelectedValue.Split(New Char() {":", " "})
Dim hours As Integer = Integer.Parse(time(0))
Dim minutes As Integer = Integer.Parse(time(1))
Dim ampm As Integer = 12
If time(2).ToLower() = "am" Then
ampm = 0
End If
Dim dt As DateTime = DateTime.Today.AddHours(hours + ampm).AddMinutes(minutes)
Have a look at DateTime.TryParse and DateTime.Today. Using them should be enough to do what you want.
Untested Code.
DateTime dt;
if (DateTime.TryParse(Dropdown1.SelectedValue, out dt))
{
DateTime result = DateTime.Today.AddHours(dt.Hour).AddMinutes(dt.Minute);
}
Basically, you just need to parse the time string. It will be automatically resolved to the current date.
Dim strTime As String = "8.30am"
Dim parsedTime As DateTime
If DateTime.TryParseExact(strTime, "h.mmtt", New System.Globalization.DateTimeFormatInfo(), Globalization.DateTimeStyles.None, parsedTime) = True Then
'Parse was successful.
Else
'Handle the error.
End If
Store as the value for each drop down item the number of minutes from midnight that the time represents. Then:-
valueToStore = DateTime.Today + TimeSpan.FromMinutes(Int32.Parse(value))
By storing using the value attribute of a HTML option to store a simple representation of the value you eliminate the codes dependancy on the actual format used to simply display the set of values. If it decided that the representation of the times be changed to use different format the rest of the code will continue to work unmodified.
var time = this.DropDownList1.SelectedValue.Split(':', ' ');
var hours = Int32.Parse(time[0]);
var minutes = Int32.Parse(time[1]);
var ampm = (time[2] == "PM") ? 12 : 0;
var dt = DateTime.Today.AddHours(hours + ampm).AddMinutes(minutes);
Parse your DropDownList for Hours and Minutes, then add them to DateTime.Today.
Read the parts of the time so you have hours and minutes, then use the following code:
DateTime myDate = DateTime.Now.Date;
myDate = myDate.AddHours(hours);
myDate = myDate.AddMinutes(minutes);
Use ParseExact so that you can specify the format that you are using.
h = hours in 12-hour clock format
. = literal character
mm = minutes as two digits
tt = AM/PM designator
Dim time As DateTime = DateTime.ParseExact(dropdown.SelectedValue, "h.mmtt", CultureInfo.InvariantCulture)
The components of the DateTime value that you don't specify in the string (year, month, date, seconds, time zone, era) uses DateTime.Today as default, which is exactly what you want in this case.
This always seems to work for me. May not be the most elegant way, but I have not had any issues so far.
dTime = DateTime.Now;
string time = this.DropDownList1.SelectedValue;
DateTime FormattedDateTime = Convert.ToDateTime(dTime.Date.ToShortDateString() +
" " + time);
Related
i want to get a datetime value from excel sheet and take the highest and the lowest date
i read the excel sheet and put it in datatable :
i tried this code :
protected void CheckTheFP(DataTable data)
{
if (data.Rows.Count != 0)
{
DateTime ds = new DateTime();
err.Text = DateTime.TryParseExact(data.Rows[0][2].ToString(), "MM/dd/yy hh:mm tt",
CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out ds) + "" ;
}
}
but i always get false ... don't know why ?
and is there a way to sort this datatable or take the highest and lowest date
this the excel sheet i read from
This format string should work: "M/dd/yy h:mm tt". I've used single M because the month has one digit, the same applies to the hours. I've used CultureInfo.InvariantCulture to prevent that all / will be replaced with your actual date-separator (in case that it's different).
You can use LINQ:
var allDateTimes = data.AsEnumerable()
.Select(row => DateTime.ParseExact(row.Field<string>("Time"), "M/dd/yy h:mm tt", CultureInfo.InvariantCulture));
DateTime min = allDateTimes.Min();
DateTime max = allDateTimes.Max();
If you want to be on the safe side you should use TryParseExact, for example with this code:
IEnumerable<DateTime> allDateTimes = data.AsEnumerable()
.Select(row => {
string time = row.Field<string>("Time").Trim();
DateTime dt;
if (DateTime.TryParseExact(time, "M/dd/yy h:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
return (DateTime?) dt;
return null; // set a breakpoint here to see which value could not be parsed
})
.Where(dt => dt.HasValue)
.Select(dt => dt.Value);
DateTime min = allDateTimes.Min();
DateTime max = allDateTimes.Max();
Edit: you: "when i try to use it on the date 11/2/14 4:42 PM you see the 11 is not in M datetime format
The month is not the problem. Use single d instead because the days can have a single digit also.
So: "M/d/yy h:mm tt"
I want to change the date format
CultureInfo ci = new CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture = ci;
string fromdate =(TxtFrom.Text);
string todate = (TxtTo.Text);
DateTime dt =DateTime.Parse(fromdate);
DateTime d =DateTime.Parse(todate);
_DivAPath.FROM_DATE = Convert.ToDateTime("d",ci);
_DivAPath.TO_DATE = Convert.ToDateTime("d",ci);
But it will show exception that the given Datetime is not a correct format.how to change the datetime function...
please explain
First, you don't need to actually change the culture if you want to parse or convert dates with a given CultureInfo, so this is unnecessary:
Thread.CurrentThread.CurrentCulture = ci;
You can simply use the DateTime.Parse overload that accepts the culture:
DateTime dt = DateTime.Parse(fromdate, ci);
The exception is probably raised at Convert.ToDateTime("d",ci); since d is not a valid date ;)
Maybe FROM_DATE is a string property and you actually want to convert the datetime to a short-date-string, then you could either use:
_DivAPath.FROM_DATE = dt.ToString("d", ci);
or
_DivAPath.FROM_DATE = dt.ToShortDateString(); // uses the current-culture
You are passing the String "d" as a value to convert to DateTime. Pass d and dt without the quotation marks.
I have a month key which look like this "201208".
I am reading the data from SQL and returning as a DataTable.
Then I am looping through my DataTable.
For Each dr As DataRow In dt.Rows
Dim s As String = dr.Item(0)
Next
My s would be a string looking like this "201208"
How convert this string into year, first day of the month and last day of the month?
Looking for a way to split the string into two seperate dims.
Any suggestions much appreciated.
The easiest way is to just parse the string as Date, then calculate the last day of the month.
Try the following:
Dim s = "201208"
Dim firstDay = Date.ParseExact(s, "yyyyMM", Nothing)
Dim lastDay = firstDay.AddMonths(1).AddDays(-1)
Dim year = firstDay.Year
Firstly I would use DateTime.TryParseExact Method with format "ddMMyy" to parse the string into a DateTime.
Then I would use something like
Dim startDate As New DateTime(dbDate.Year, dbDate.Month, 1)
Dim endDate As DateTime = startDate.AddMonths(1).AddDays(-1)
to get the StartDate and EndDate
This works for me:
Function FormatDate(ByVal dateKey As String) As String
Dim x As DateTime = DateTime.ParseExact(dateKey, "yyyyMM", Nothing)
FormatDate = String.Format("Year: {0}; First day of month: {1}; Last day of month: {2}", x.Year, x.AddDays(-x.Day).ToString("dddd"), x.AddMonths(1).AddDays(-x.Day).ToString("dddd"))
End Function
You can use this function as so:
Dim dateDetails As String = FormatDate("201208")
Split that string into a year and month (see Substring)
Use "1" as the first of the month -> that's your start date
Add one month, subtract one day -> that's your end date
I'm doing the following query to check if the current month is the same as the SQL field "Start".
If Today.Month = CDate(rsData("Start")).Month Then
What I'd like to do is switch it so that it will check within a 30 day period rather than identify the current month? Any ideas on how to do this?
If Date.Today.AddDays(-30) >= CDate(rsData("Start"))
' start date not older than 30 days '
End If
or if you have a variable date:
var minBoundary = New Date(2011,1,1)
var maxBoundary = New Date(2012,1,1)
var startDate = CDate(rsData("Start"))
If startDate >= MinBoundary AndAlso startDate <= maxBoundary
' start date between two dates '
End If
I believe in this case you would want to use the AddDays method of DateTime.
Dim mydate as DateTime = CDate(rsData("Start"))
Dim checkdate as DateTime = mydate.AddDays(30)
is there any ready to go solution within the microsoft framework, regarding conversion of date to day?
For example, i would like to convert this string 21/03/2010 (dd/mm/yyyy) to Sunday
Dim d = DateTime.Parse("21/03/2010").DayOfWeek()
This code will print Sunday on the console window
Dim dateToShow as DateTime = new DateTime(2010, 03,21)
Console.WriteLine(dateToShow.DayOfWeek.ToString)
This should print "Sunday".
string myDateTimeString = "21/03/2010";
DateTime dt = DateTime.ParseExact(
myDateTimeString, "dd/MM/yyyy",
new CultureInfo("en-Us", true)
, DateTimeStyles.NoCurrentDateDefault);
Console.WriteLine(dt.DayOfWeek);
I would use DateTime.TryParse() just to validate the user input.
Dim input As String = "2010/12/23"
Dim dateTime As DateTime
If DateTime.TryParse(input, dateTime) Then
Console.WriteLine(dateTime.DayOfWeek)
Else
Console.WriteLine("Invalid")
End If