Changing Only Time in DateTime Format - MVC 4 - asp.net

I've been working with the following Lynda.com tutorial on learning MVC 4 and Razor. I'm stuck on trying to have the time that's displayed only shows the hours, minutes, then AM/PM. As of now, the screen still includes the seconds (as seen below):
I tried formatting my dates like this post about DateTime, which didn't work. Now I have the following code within my function in the controller section entitled "AuctionsController.vb", similar to this post:
Function Auction() As ActionResult
Dim mainauction = New MVCAuction3.Models.Auctions
Dim ts As New TimeSpan(10, 0, 0)
mainauction.Title = "Example Auction"
mainauction.Description = "This is an example Auction"
mainauction.StartTime = DateTime.Now + ts
mainauction.EndTime = DateTime.Now.AddDays(7) + ts
mainauction.StartPrice = 1.0
mainauction.CurrentPrice = Nothing
ViewData("Auction") = mainauction
Return View()
End Function
This is how Razor is displaying the content from the view "Auction.vbhtml":
<p>Start Time: #auction.StartTime.ToString() </p>
<p>End Time: #auction.EndTime.ToString()</p>
<p>Starting Price: #FormatCurrency(auction.StartPrice.ToString())</p>
Edit(s):
This is how I declared my time variables in my modal file:
Private Property x_StartTime As DateTime
Private Property x_EndTime As DateTime
Public Property StartTime() As DateTime
Get
Return x_StartTime
End Get
Set(value As DateTime)
x_StartTime = value
End Set
End Property
Public Property EndTime() As DateTime
Get
Return x_EndTime
End Get
Set(value As DateTime)
x_EndTime = value
End Set
End Property
I've also tried to have it from within the "Auction.vhtml" view the following, which unfortunately gave me the server error indicating the "Input string was not in a correct format.":
<p>Start Time: #auction.StartTime.ToString("g") </p>
<p>End Time: #auction.EndTime.ToString("g")</p>
<p>Starting Price: #FormatCurrency(auction.StartPrice.ToString())</p>
What am I doing wrong in either the Razor or MVC code that is not formatting the time? Any help is greatly appreciated!

You should take a look at Custom Date and Time Format Strings on MSDN. Basically, you can pass a format string to the ToString method of your DateTime objects.
Here's a sample that omits the seconds:
auction.StartTime.ToString("M/d/yyyy hh:mm tt")

I would highly suggest looking into the DisplayFormat (MSDN) attribute. You would append it to your models StartTime property like so
[DisplayFormat(ApplyFormatInEditMode=true, DataFormatString = "{0:M/d/yyyy hh:mm tt}")]
public DateTime StartTime {get;set;}
and then you would output the information in your view by the DisplayFor function:
#Html.DisplayFor(x=> x.StartTime)

Related

Calculating the difference in days of two dates stored in ajax calendar extender controls

I am looking to find the difference in days of two ajax calendar extenders that are linked to two separate text boxes.
Dim dt1 As DateTime = Convert.ToDateTime(CalendarExtender1.SelectedDate)
Dim dt2 As DateTime = Convert.ToDateTime(CalendarExtender2.SelectedDate)
Dim diffInDays As Integer = dt2.Subtract(dt1).Days
Label12.text = "The dates are " + diffInDays.ToString() + "days appart."
I have completed this task using the asp calendar control previously but I am having issues when trying to achieve this using the ajax calendar extension.
the label output is stating " the two dates are 0 days apart " for numerous tested dates.
I would appreciate if anyone could give any guidance/help or let me know where i am going wrong.
Thanks!
Use the TimeSpan object :)
Hacky example:
Sub Main()
Console.WriteLine(getDayDifference(CDate("2017-06-03"), CDate("2017-06-03"), True).ToString)
Console.WriteLine(getDayDifference(CDate("2017-06-03"), CDate("2017-05-03"), True).ToString)
Console.WriteLine(getDayDifference(CDate("2017-02-03"), CDate("2017-05-03"), True).ToString)
Console.ReadKey()
End Sub
Public Function getDayDifference(first As DateTime, second As DateTime, alwaysPositive As Boolean)
Dim span As TimeSpan = second - first
Return If(alwaysPositive, Math.Abs(span.TotalDays), span.TotalDays)
End Function
Will return:
0
31
89
You can set the alwaysPositive arg to False if you want the true polarity (helpful when determining if the first date is lower than the second), eg:
0
-31
89

XPages sessionScope variable and DateTime values

I seem to be losing the value of sessionScope variables between XPages when I load DateTime values from a Notes document (not from the XPage). Here is what I do:
I have an EditBox where the contents are set to type Date only:
<xp:inputText value="#{document1.datum}" id="datum" defaultValue="#{javascript:#Now()}" required="true">
<xp:this.converter>
<xp:convertDateTime type="date"></xp:convertDateTime>
</xp:this.converter>
<xp:dateTimeHelper></xp:dateTimeHelper>
</xp:inputText>
I then save this to a sessionScope variable :
sessionScope.put ("datum", getComponent("datum").getValue());
Then I change XPages by doing a:
var extCont = facesContext.getExternalContext();
extCont.redirect("xpNextPage.xsp")
I then do a sessionScope.get:
print (sessionScope.get ("datum"));
And the contents are fine.
if I do the same thing with a document that I have loaded:
var date:NotesDateTime = doc.getItemValueDateTimeArray("datum");
var start:NotesDateTime = doc.getItemValueDateTimeArray("von");
var dt:NotesDateTime = session.createDateTime (date [0].getDateOnly() + " " + start [0].getTimeOnly());
sessionScope.put ("datum", dt);
then switch to the next page and try and load it with:
print (sessionScope.get ("datum"));
I get a value null.
I have attached a screenshot of the problem (I printed other fields as well so you can see it is only the DateTime fields that are the problem). I do notice that the format of the DateTime value is different... could this be the problem?
NotesDataTime is not serializable, so you cannot store it in the memory. When you use getComponent("datum").getValue(), it returns you Java Date not NotesDataTime. Java date is serializable, so its working.
Try convert your NotesDataTime to Java Date.
dt.toJavaDate()

Date field changing from UK to US culture upon SaveChanges (EF6.1)

I am using a custom overloaded SaveChanges to implement some auditing functionality. The functionality works perfectly with the exception of some unexpected behaviour in relation to dates. In this example I'm changing a date field value from 1st May 2014 to 2nd May 2014:
A change is made to the database here:
Public Function UpdateTask(request As DataSourceRequest, ThisTask As JobTasksVM) As JsonResult
Dim cu As ApplicationUser = GetCurrentUser()
Dim CurrentTask = db.events.Find(ThisTask.id)
CurrentTask.start_date = ThisTask.start '<--- 2/5/2014 (ie 2nd May 2014), was previously 1/5/2014
CurrentTask.date = ThisTask.end
CurrentTask.task_name = ThisTask.Title
db.SaveChanges(cu.Employee_id)
End Function
This is intercepted by my custom SaveChanges:
Public Overloads Function SaveChanges(userID As Integer) As Integer
For Each entry As dbentityentry In Me.ChangeTracker.Entries().Where(Function(e) e.State <> EntityState.Unchanged)
Dim startOriginal As DateTime = entry.OriginalValues.Item("start_date")
Dim StartCurrent As DateTime = entry.CurrentValues.Item("start_date")
etc....
The bizarre thing is that whilst CurrentTask.start_date that is committed clearly shows the correct (UK) date of 2/5/2014 (2nd May 2014) the values within the overloaded SaveChanges are:
startOriginal: 5/1/2014 (ie 5th Jan 2014) <-- seems to have changed to US culture
startCurrent: 2/5/2014 (ie 2nd May 2014) <---as expected
I need to use the Original values in my audit functionality so this is causing a problem. I have also tried:
entry.CurrentValues.SetValues(entry.GetDatabaseValues)
But this also loads in the erroneous (ie US format 5/1/2014) into the start_date field.
I've checked all the culture settings on the system and they are all correctly English-UK. This behaviour seems fundamentally inconsistent - am I missing something?!
Thanks
DateTime types do not have a format, they are simply a value (number of ticks since 1/1/0001).
You did not say where you are seeing the "wrong" format, whether ToString() output or in intellisense. If you use ToString to the Output window, you should see the UK format since ToString will use/respect the local culture setting of the computer.
Intellisense is culture agnostic and tries to use an unambiguous format: MM/dd/yyyy. This is the same "format" or order you have to use when creating a DateTime var from a literal:
Dim dt As DateTime = #1/5/2014# ' e.g. MM/dd/yyyy
' same as:
Dim dt As New DateTime(1, 5, 2014) ' mm, dd, yyyy
This is InvariantCulture (not US). When you hold the mouse over the var, the VB IDE will use the same order. It tries to make clear it is using the required literal/InvariantCulture format by displaying it with the hashes: #1/5/2014#.
Dim dt As DateTime = #2/11/2011#
Console.WriteLine(dt.ToString)
In the US, 2/11/2011 will display based on the culture
In the UK, it will be 11/2/2011
Intellisense will be #2/11/2011#

VB6 - "Time-Formatted" Datepicker passes invalid date (below 1/1/1900)

I have a VB6 Datepicker with the following properties:
Format Type - Time
Min Date - 1/1/1900
Value - 12:00:00 AM
And I initialize it like this:
dtpTimeVal = TimeValue("00:00:00")
However, when I get the date value of the time picker, it returns the value 12/30/1899.
Am I missing any properties or initialization logic here?
there probably is some error where you set the format
the following works:
Private Sub Form_Load()
DTPicker1.Format = dtpTime
DTPicker1.Value = "00:00:00"
End Sub
if i remove the format line, then i get the same result as you do

Convert string 10/29/2010 according to users culture

How can I convert the english date 10/29/2010 or any language date to user culture date format
I am using the following code
CultureInfo cultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture;
cultureInfo.DateTimeFormat.
string lng = cultureInfo.TwoLetterISOLanguageName;
DateTime dateTime = DateTime.Parse("10/29/2010", cultureInfo);
but it throws error when I try to parse it.
Any Idea how can I resolve this issue
Thanx
Use ParseExact with English (or invariant) culture to convert the String into a datetime, then you can use ToString to output in in the user's date format.
// this is in "d" (= short date) format of the invariant culture
var englishDateString = "10/29/2010";
// convert it to a datetime
var date = DateTime.ParseExact(englishDateString, "d", CultureInfo.InvariantCulture);
// now you can output the date in the user's culture
var localizedDateString = date.ToString("d");
If you want to be explicit, you can add CultureInfo.CurrentCulture as a second parameter to ToString, but it's not required, since this is the default if no culture is specified.
Here's an example of parsing a US date:
DateTime.Parse("10/29/2010", new CultureInfo("en-US"));
i had the same pain when facing date conversion and i used a function (code below), you can modify it as you wish. try it or get ideas from it and let me know if it was useful
Imports Microsoft.VisualBasic Imports System.Globalization Public Class DatumKonvert1
Public Shared Function DK1(ByVal myDMstring As String) As Date
Dim source As String = myDMstring
Dim d As DateTime = DateTime.ParseExact(source, "d'/'M'/'yyyy", CultureInfo.InvariantCulture)
Dim resultMydate As String = d.ToString("M'/'d'/'yyyy")
Dim mdx = DateTime.ParseExact(resultMydate, "M'/'d'/'yyyy", CultureInfo.InvariantCulture)
Return mdx End Function End Class
Use this:
public static string ChangeDateToUserFormat(string dateValue, string dateCulture)
{
CultureInfo dateCultureInfo = CultureInfo.GetCultureInfoByIetfLanguageTag(dateCulture);
DateTime date = DateTime.Parse(dateValue, dateCultureInfo);
return date.ToString(CultureInfo.CurrentCulture);
}
For example:
string date = ChangeDateToUserFormat("10\29\2010", "en-US");
Use DateTime.ParseExact("10/29/2010", "MM/dd/yyyy", CultureInfo.InvariantCulture); instead of DateTime.Parse
Once you have a DateTime, it is no longer bound to a specific culture, but can be output however you want it. Usually, this is with one of the DateTime .ToString methods, or shortcuts like .ToShortDateString(), which uses the current thread's culture.
Edit: Note, it helps if I put the month and day ones in the correct spots. Whoops.

Resources