Navigation

Search

Categories

On this page

Using XMLHttpRequest
Clearing a Form In ASP.NET
Google AJAX Search API
Javascript/AJAX Library
Using XP_EXECRESULTSET To Obtain Database Size Information
SQL Web Data Administrator
AJAX-Style Loading Icons
Checking for null values in Request.Querysting
The Format() Function
Formatting Dates and Times
Formatting Percentages
Formatting Numbers
Formatting Currency
Preventing Duplicate Logins
Date and time functions

Archive

Blogroll

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

Total Posts: 112
This Year: 50
This Month: 0
This Week: 0
Comments: 0

Sign In

 Tuesday, July 03, 2007
Tuesday, July 03, 2007 12:48:50 PM (Eastern Standard Time, UTC-05:00) ( )

A coworker passed along this link from IBM which provides a nice series of tutorials on AJAX. The example below is a classic example of how to use the XMLHTTPRequest object while checking for different browser types and then using the server's response for something.

<script language="javascript" type="text/javascript">
var request = false;
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}

if (!request)
alert("Error initializing XMLHttpRequest!");

function getCustomerInfo() {
var phone = document.getElementById("phone").value;
var url = "/cgi-local/lookupCustomer.php?phone=" + escape(phone);
request.open("GET", url, true);
request.onreadystatechange = updatePage;
request.send(null);
}

function updatePage() {
if (request.readyState == 4) {
if (request.status == 200) {
var response = request.responseText.split("|");
document.getElementById("order").value = response[0];
document.getElementById("address").innerHTML = response[1].replace(/\n/g, "<br />");
} else if (request.status == 404) {
alert ("Requested URL is not found.");
} else if (request.status == 403) {
alert("Access denied.");
} else
alert("status is " + request.status);
}
}

</script>

<body>
<p><img src="breakneck-logo_4c.gif" alt="Break Neck Pizza" /></p>
<form action="POST">
<p>Enter your phone number:
<input type="text" size="14" name="phone" id="phone"
onChange="getCustomerInfo();" />
</p>
<p>Your order will be delivered to:</p>
<div id="address"></div>
<p>Type your order in here:</p>
<p><textarea name="order" rows="6" cols="50" id="order"></textarea></p>
<p><input type="submit" value="Order Pizza" id="submit" /></p>
</form>
</body>

Tuesday, July 03, 2007 8:07:15 AM (Eastern Standard Time, UTC-05:00) ( )

Clearing a form of all entries or values is a common task in HTML but seemed to be a bit more challenging in ASP.NET.  It seemed the only way to do this was by posting the page back to itself using server.transfer("page.aspx")

I just stumbled across this method new to ASP.NET 2.0 using OnClientClick and it works great.

<asp:Button ID="btnReset" CssClass="smalltext" OnClientClick="Form1.reset();return false;" runat="server" Text="Clear Form" />

HTML version:

<input type="reset" value="Clear Form" name="Reset" onclick="ResetControls(this.form)">

 Monday, July 02, 2007
Monday, July 02, 2007 11:48:54 AM (Eastern Standard Time, UTC-05:00) ( )

Google makes a cool API that utilizes AJAX to which allows developers to add a Web or local search to their sites relatively easily. 

I created an example of it here: http://www.stonecoastwebdesign.com/search/example.htm

Monday, July 02, 2007 9:37:01 AM (Eastern Standard Time, UTC-05:00) ( )

A co-worker passed this along to me which looks pretty cool

http://extjs.com/

 Tuesday, June 26, 2007
Tuesday, June 26, 2007 10:01:39 PM (Eastern Standard Time, UTC-05:00) (  |  )

Came across this article and code which provides a script for obtaining the size of every database on your SQL Server 2000 box. Very nice...

http://www.sqlservercentral.com/columnists/jtshyman/usingxp_execresultsettoobtaindatabasesizeinformati.asp

Tuesday, June 26, 2007 9:56:40 PM (Eastern Standard Time, UTC-05:00) ( )

I came across this nifty web-based administrator for SQL Server from Codeplex.   I haven't tried it yet but it looks promising and it's open source.

 

 

 Monday, June 25, 2007
Monday, June 25, 2007 11:52:42 AM (Eastern Standard Time, UTC-05:00) ( )

Some useful icons for displaying those "loading" messages used in AJAX-enabled applications.

 

 Friday, June 22, 2007
Friday, June 22, 2007 9:36:56 AM (Eastern Standard Time, UTC-05:00) ( )

Something I do all of the time and I think this the best method to do it

If Not Request.QueryString("DashboardID") Is Nothing andalso Request.QueryString("DashboardID").trim.length > 0 then

 Thursday, June 21, 2007
Thursday, June 21, 2007 8:21:22 PM (Eastern Standard Time, UTC-05:00) ( )

The Format() Function

The Format() function is a general-purpose formatting function that returns a string value formatted according to a format string. The format strings duplicate numeric and date/time formats produced by the specialized formats described above. The general format for applying the Format() function is shown below.

Format(value, "format string")

Formatting Numbers

A format string for numeric values can use one of the predefined string values shown in the following table.

String Description
General Number|G|g Displays number with no thousand separator.
Currency|C|c Displays number with thousand separator, if appropriate; display two digits to the right of the decimal separator.
Fixed|F|f Displays at least one digit to the left and two digits to the right of the decimal separator.
Standard|N|n Displays number with thousand separator, at least one digit to the left and two digits to the right of the decimal separator.
Percent Displays number multiplied by 100 with a percent sign (%) appended immediately to the right; always displays two digits to the right of the decimal separator.
P|p Displays number with thousandths separator multiplied by 100 with a percent sign (%) appended to the right and separated by a single space; always displays two digits to the right of the decimal separator.

Examples of applying a format string to numeric values are shown in the following table.

Format Output
Format(12345.6789,"g") 12345.6789
Format(12345.6789,"c") $12,345.68
Format(12345.6789,"f") 12345.68
Format(12345.6789,"n") 12,345.68
Format(-12345.6789,"g") -12345.6789
Format(-12345.6789,"c") ($12,345.68)
Format(-12345.6789,"f") -12345.68
Format(-12345.6789,"n") -12,345.68
Format(.6789,"Percent") 67.89%
Format(.6789,"p") 67.89 %
Format(-.6789,"Percent") -67.89%
Format(-.6789,"p") -67.89 %

Formatting Dates and Times

A format string for date/time values can use one of the predefined string values shown in the following table.

String Description
Long Date|D Displays a date in long date format.
Short Date|d Displays a date in short date format.
Long Time|T Displays a date in long date format.
Short Time|t Displays a date in short date format.
F Displays the long date and long time.
f Displays the long date and short time.
g Displays the short date and short time.
M|m Displays the month and the day of a date.
Y|y Formats the date as the year and month.

Examples of applying a format string to date/time values are shown in the following table.

Format Output
Format(Now,"D") Thursday, June 21, 2007
Format(Now,"d") 6/21/2007
Format(Now,"T") 9:10:57 PM
Format(Now,"t") 9:10 PM
Format(Now,"F") Thursday, June 21, 2007 9:10:57 PM
Format(Now,"f") Thursday, June 21, 2007 9:10 PM
Format(Now,"g") 6/21/2007 9:10 PM
Format(Now,"m") June 21
Format(Now,"y") June, 2007

User-defined Numeric Formats

Formats can be defined for displaying numeric values by composing a string to describe the format. This user-defined string is applied through the Format() function. The characters shown in the following table are used to compose the format string.

Character Description
0 Digit placeholder. Displays a digit or a zero. If the value has a digit in the position, then it displays; otherwise, a zero is displayed.
# Digit placeholder. Displays a digit or a space. If the value has a digit in the position, then it displays; otherwise, a space is displayed.
. Decimal placeholder; determines how many digits are displayed to the left and right of the decimal separator.
, Thousand separator; separates thousands from hundreds within a number that has four or more places to the left of the decimal separator. Only a single "," is required in the format, between the first set of digit placeholders.
% Percent placeholder. Multiplies the expression by 100. The percent character (%) is inserted in the position where it appears in the format string.
- + $ ( ) Literal characters; displayed exactly as typed in the format string.

Examples of applying a user-defined format string to numeric values are shown in the following table.

Format Output
Format(012345.6789,"0.00") 12345.68
Format(012345.6789,"0,0.000") 12,345.679
Format(012345.6789,"00000,0.000000") 012,345.678900
Format(012345.6789,"#.##") 12345.68
Format(012345.6789,"#,#.##") 12,345.68
Format(012345.6789,"$ #,#.##") $ 12,345.68
Format(-012345.6789,"#,#.####") -12,345.6789
Format(-012345.6789,"$#,#.##") -$12,345.68
Format(.6789,"#,#.##") .68
Format(.6789,"0,0.000") 00.679
Format(-.6789," 0.0000") - 0.6789
Format(.6789,"0.00%") 67.89%

User-defined Date/Time Formats

Formats can be defined for displaying date and time values by composing a string to describe the format. This user-defined string is applied through the Format() function. The characters shown in the following table are used to compose the date/time format string.

Character Description
: Time separator.
/ - Date separators.
% Precedes a single-character format string.
d Displays the day as a number without a leading zero.
dd Displays the day as a number with a leading zero.
ddd Displays the day name as an abbreviation.
dddd Displays the day as a full name.
M Displays the month as a number without a leading zero.
MM Displays the month as a number with a leading zero.
MMM Displays the month name as an abbreviation.
MMMM Displays the month as a full name.
yy Displays the year in two-digit format.
yyyy Displays the year in four-digit format.
h Displays the hour as a number without leading zeros using the 12-hour clock.
hh Displays the hour as a number with leading zeros using the 12-hour clock.
H Displays the hour as a number without leading zeros using the 24-hour clock.
HH Displays the hour as a number with leading zeros using the 24-hour clock.
m Displays the minute as a number without leading zeros.
mm Displays the minute as a number with leading zeros.
s Displays the seconds as a number without leading zeros.
ss Displays the seconds as a number with leading zeros.
f... Displays fractions of seconds using up to 7 characters to display fractional digits.
tt Uses the 12-hour clock and displays an uppercase AM with any hour before noon; displays an uppercase PM with any hour between noon and 11:59 P.M.
  Additional characters and punctuation marks can be used within the format string. Characters that match any of the formatting characters must be preceded by "\".

Examples of applying a user-defined format string to date/time values are shown in the following table.

Format Output
Format(Now,"M/d/yy") 6/21/07
Format(Now,"M-d-yyyy") 6-21-2007
Format(Now,"d-MMMM-yy") 21-June-07
Format(Now,"d MMMM, yyyy") 21 June, 2007
Format(Now,"MMMM d, yyyy") June 21, 2007
Format(Now,"MMMM, yyyy") June, 2007
Format(Now,"%d") 21
Format(Now,"h:m tt") 9:10 PM
Format(Now,"h:m:ss tt") 9:10:57 PM
Format(Now,"H:m") 21:10
Format(Now,"M/d/yy - h:mtt") 6/21/07 - 9:10PM
Format(Now,"H:m:ss.fffffff") 21:10:57.5829544
Format(Now,"To\da\y i\s MMMM d, yyyy.") Today is June 21, 2007.

Thursday, June 21, 2007 8:19:00 PM (Eastern Standard Time, UTC-05:00) ( )

FormatDateTime(Now) 6/21/2007 9:10:57 PM
FormatDateTime(Today) 6/21/2007
FormatDateTime(TimeOfDay) 9:10:57 PM
FormatDateTime(Now,DateFormat.LongDate) Thursday, June 21, 2007
FormatDateTime(Today,DateFormat.LongDate) Thursday, June 21, 2007
FormatDateTime(Now,DateFormat.ShortDate) 6/21/2007
FormatDateTime(Today,DateFormat.ShortDate) 6/21/2007
FormatDateTime(Now,DateFormat.LongTime) 9:10:57 PM
FormatDateTime(TimeOfDay,DateFormat.LongTime) 9:10:57 PM
FormatDateTime(Now,DateFormat.ShortTime) 21:10
FormatDateTime(TimeOfDay,DateFormat.ShortTime) 21:10

Thursday, June 21, 2007 8:18:24 PM (Eastern Standard Time, UTC-05:00) ( )

Format Output
FormatPercent(.6789) 67.89%
FormatPercent(.6789,4) 67.8900%
FormatPercent(-.6789) -67.89%
FormatPercent(-.6789,,,True) (67.89%)

Thursday, June 21, 2007 8:17:43 PM (Eastern Standard Time, UTC-05:00) ( )

Format Output
FormatNumber(12345.6789) 12,345.68
FormatNumber(12345.6789,5) 12,345.67890
FormatNumber(12345.6789,,,,False) 12345.68
FormatNumber(-12345.6789) -12,345.68
FormatNumber(-12345.6789,,,True) (12,345.68)
FormatNumber(.6789) 0.68
FormatNumber(.6789,,False) .68
FormatNumber(-.6789,4) -0.6789

Thursday, June 21, 2007 8:17:03 PM (Eastern Standard Time, UTC-05:00) ( )

Format Output
FormatCurrency(12345.6789) $12,345.68
FormatCurrency(12345.6789, 4) $12,345.6789
FormatCurrency(12345.6789,,,,False) $12345.68
FormatCurrency(-12345.6789) ($12,345.68)
FormatCurrency(-12345.6789,,,False) -$12,345.68
FormatCurrency(.6789) $0.68
FormatCurrency(.6789,,False) $.68
FormatCurrency(-.6789,,False,False) -$.68

 Monday, June 18, 2007
Monday, June 18, 2007 11:21:48 AM (Eastern Standard Time, UTC-05:00) (  |  )

I recently had to put into place a method that prevented more than one user from logging into our company web site under the same login ID. With the help of a friend, this is what we came up with. 

Basically, each time a user logs in, the user's UserID and sessionID are stored in a database table at login.  Each time the user visits a page in the site, the user's session ID is matched against what is stored in the database.  If the sessionIDs do not match, then the user is logged out and redirected to a page that says something like "duplicate login detected.  you're a cheating bum. etc."

A typical scenario would work like this:

User A logs into the site and the sessionID is recorded into the dbase. She browses from page and page within the site and on each page her sessionID is verified against what's stored in the database.

User B then logs into the site using User A's ID and password. The sessionID information stored in the database for User A is overwritten by User B. When user A tries to browse to another page, she receives a message stating that someone has logged into the site using her ID.  User A can log back in, but then User B will receive the duplicate login message and round and round they go.

Here's the code for it.

This stored procedure is called on the login page. If the user's userID is not already in the datbase, then it is inserted as a new record. Otherwise, the existing record is updated with the new session ID.

CREATE Procedure sp_LoginStatusCheck
@UserID as Int,
@SessionID as nvarchar(100)


AS
    IF (SELECT COUNT(UserID)
FROM TLoginStatus
WHERE UserID = @UserID) = 0
        
BEGIN
INSERT INTO TLoginStatus(UserID, SessionID) Values (@UserID, @SessionID)
    
END
ELSE
         UPDATE TLoginStatus
         SET SessionID = @SessionID
         WHERE UserID = @UserID
GO

Call sp_LoginStatusCheck in the login page.

Sub AddSessionCheck(ByVal UserID As Integer)
'Due to some bizarre requirement that there must be some value assigned to a Session variable not to lose
'the value for SessionID, I created a random session variable and value            
Session("BA") = "BA"
            
            
Dim myConnection As SqlConnection
Dim cmd As SqlCommand
            
myConnection = New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
cmd = New SqlCommand("sp_LoginStatusCheck", myConnection)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("@UserID", SqlDbType.Int, 4).Value = UserID
cmd.Parameters.Add("@SessionID", SqlDbType.NVarChar, 100).Value = Session.SessionID
                        
Try
myConnection.Open()
cmd.ExecuteNonQuery()
Finally
myConnection.Close()
End Try

End Sub


On each page that I Want to check for a duplicate login, I would first get the userID value which is stored in a cookie value in the Page_Load function. 

<%@ Page Language="VB" Inherits="MyBaseClass" src="~/classes/MyBaseClass.vb" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
Sub Page_Load()
If Not IsPostBack Then
Dim strUserID As String
If Not IsNothing(Request.Cookies("BA")) Then
strUserID = Request.Cookies("BA")("UserID").ToString()
lblUserID.Value = strUserID
End If


'Call CheckLoginStatus
    CheckLogin(strUserID)
    
End If
End Sub
</script>

I created a new class called MyBaseClass with a sub called CheckLogin that accepts UserID as a parameter. This gets called on every page that I check.

Imports Microsoft.VisualBasic
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.Configuration
Imports System.Web.HttpContext

Public Class MyBaseClass
Inherits System.Web.UI.Page

Public Shared Sub CheckLogin(ByVal UserID As Integer)

'This entire section is the duplicate login prevention section
System.Web.HttpContext.Current.Session("Spice") = "Ginger"
Dim strSessionID = System.Web.HttpContext.Current.Session.SessionID
Dim strLoginStatus As String

Dim MyConnection As SqlConnection
Dim Cmd As SqlCommand

MyConnection = New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
Cmd = New SqlCommand("sp_LoginStatusCheck2", MyConnection)
Cmd.CommandType = CommandType.StoredProcedure
Cmd.Parameters.Add("@UserID", SqlDbType.Int, 4).Value = UserID
Cmd.Parameters.Add("@SessionID", SqlDbType.NVarChar, 100).Value = strSessionID
Cmd.Parameters.Add("@LoginStatus", SqlDbType.Bit).Direction = ParameterDirection.Output

Try
MyConnection.Open()
Cmd.ExecuteNonQuery()
strLoginStatus = Cmd.Parameters(2).Value
'System.Web.HttpContext.Current.Response.Write(strLoginStatus)
Finally
MyConnection.Close()
End Try

If strLoginStatus = "False" Then
System.Web.HttpContext.Current.Response.Redirect("/duplicate.login.aspx")
End If

End Sub

End Class

Here's the code for the stored procedure sp_LoginStatusCheck2

CREATE Procedure sp_LoginStatusCheck2
@UserID as Int,
@SessionID as nvarchar(100),
@LoginStatus as Bit OUTPUT

--We don't want to check the LoginStatus of enterprise level accounts UserID 884, UserID 7996
AS
IF @UserID=884
    SET @LoginStatus = 1
ELSE IF @UserID=7996 
    SET @LoginStatus = 1
ELSE    

    IF (SELECT COUNT(*) FROM TLoginStatus WHERE UserID = @UserID AND SessionID = @SessionID) > 0
        SET @LoginStatus = 1
    ELSE
        SET @LoginStatus = 0
GO

 Friday, June 15, 2007
Friday, June 15, 2007 3:49:55 PM (Eastern Standard Time, UTC-05:00) ( )

Date and Time Properties

When working with dates and times it is often necessary to know the current date and/or time. These values can be extracted from the server's system clock through the properties shown in the table below. These properties are used in several of the date and time functions described below.

Property Value
DateString Returns a String value representing the current date.
   DateString = 06-15-2007
Now Returns a Date value containing the current date and time.
   Now = 6/15/2007 3:34:34 PM
TimeOfDay Returns a Date value containing the current time of day (the date is set to 1/1/0001).
   TimeOfDay = 1/1/0001 3:34:34 PM
Timer Returns a Double value representing the number of seconds elapsed since midnight.
   Timer = 56074.6734594
TimeString Returns a String value representing the current time of day.
   TimeString = 15:34:34
Today Returns or sets a Date value containing the current date.
   Today = 6/15/2007 12:00:00 AM

Date Functions

Date functions are summarized in the following table with functions described more fully below.

Function Use
DateAdd() Returns a Date value containing a date and time value to which a specified time interval has been added.
DateDiff() Returns a Long value specifying the number of time intervals between two Date values.
DatePart() Returns an Integer value containing the specified component of a given Date value.
DateSerial() Returns a Date value representing a specified year, month, and day, with the time information set to midnight (00:00:00).
DateValue() Returns a Date value containing the date information represented by a string, with the time information set to midnight (00:00:00).
Day() Returns an Integer value from 1 through 31 representing the day of the month.
IsDate() Returns a Boolean value indicating whether an expression can be converted to a date.
Month() Returns an Integer value from 1 through 12 representing the month of the year.
MonthName() Returns a String value containing the name of the specified month.
WeekDay() Returns an Integer value containing a number representing the day of the week.

DateAdd() adds a given date interval to a date to produce a calculated date. Its general format is

DateAdd(interval, number, date)

String Unit of time interval
d Day of month (1 through 31)
y Day of year (1 through 366)
m Month
q Quarter
w Day of week (1 through 7)
ww Week of year (1 through 53)
yyyy Year

where interval is one of the string values shown in the accompanying table, number gives the number of intervals to add, and date is the date and time to which the interval is to be added. For example, the following function returns the (formatted) date six months from today.

FormatDateTime(DateAdd("m", 6, Today),
DateFormat.LongDate)
Six months from today is Saturday, December 15, 2007.

DateDiff() returns a value giving the number of identified intervals between two dates. Its general format is

DateDiff(interval, date1, date2)

where interval is a string value representing an interval type using the date values shown in the table under the DateAdd() function, and date1 and date2 are the two dates between which the interval is calculated (date1 is subtracted from date2). The following example calculates the number of shopping days until Christmas.

DateDiff( "d", Today, "12/24/" & DatePart("yyyy", Today) )
There are 192 shopping days until Christmas.

Notice that the date2 argument passes "12/24" & DatePart("yyyy", Today). The DatePart() function (see below) extracts the current year from the current date and appends it to the string so that the calculation is always based on the current year.

DatePart() extracts a specified component of a given Date. Its general format is

DatePart(part, date)

where part is a string value representing a date component using the values shown in the table under the DateAdd() function, and date is any Date value. For example, the following function determines the day of the week on January 1, 2010.

WeekdayName(DatePart("w", "01/01/2010"))
January 1, 2010 is on a Friday

DatePart() returns an integer value (Sunday = 1) representing the day of the week. This value is converted into a weekday name with the WeekDayName() function (see below).

DateSerial() returns a Date value based upon integer values representing a year, month, and day. Its general format is

DateSerial(year, month, day)

For example, the function DateSerial(5, 7, 15) returns 7/15/2005 12:00:00 AM. You might wonder why the need to return a date if you already know the date! The point is that the passed values are integers, perhaps collected from a form in which a year, month, and day are selected from drop-down lists. These integer values are combined and converted into a Date type with the DateSerial() function.

DateValue() returns a Date type from a String value representing a date. This function works as a converter to a Date data type. For example, the function call DateValue("January 1, 2005") returns 1/1/2005 12:00:00 AM.

Day() returns an Integer representing the day of the month from a passed date. For instance, function Day(Today) returns 15. This is the same value as returned from the function DatePart("d", Today).

IsDate() returns a Boolean value indicating whether the passed value can be converted into a Date type. This function is handy when testing user input to verify that an actual date has been entered. A function call in the format IsDate("02/31/2005") returns False.

Month() returns an Integer value from 1 through 12 representing the month of the year. It works similar to the Day() function. The function call Month(Today) returns 6.

MonthName() accepts an Integer representing a month of the year and returns a String value containing the name of the month. Used in conjunction with the Month() function, the function call MonthName(Month(Today)) produces June.

WeekDay() returns an Integer value between 1 and 7 (Sunday = 1) representing the day of the week. The function WeekDay(Today) returns 6, which is identical to the value returned by DatePart("w", Today).

WeekDayName() accepts an Integer representing a day of the week and returns a String value containing the name of the day of the week. Used in conjunction with the Weekday() function, the function call WeekDayName(WeekDay(Today)) produces Friday.

Time Functions

Time functions are summarized in the following table with functions described more fully below. Several of the date functions can be applied to time measurements.

Function Use
DateAdd() Returns a Date value containing a date and time value to which a specified time interval has been added.
DateDiff() Returns a Long value specifying the number of time intervals between two Date values.
DatePart() Returns an Integer value containing the specified component of a given Date value.
Hour() Returns an Integer value from 0 through 23 representing the hour of the day.
Minute() Returns an Integer value from 0 through 59 representing the minute of the hour.
Second() Returns an Integer value from 0 through 59 representing the second of the minute.
TimeSerial() Returns a Date value representing a specified hour, minute, and second, with the date information set relative to January 1 of the year 1.
TimeValue() Returns a Date value containing the time information represented by a string, with the date information set to January 1 of the year 1.

DateAdd() adds a given time interval to a time to produce a calculated time. Its general format is

DateAdd(interval, number, time)

String Unit of time interval
h Hour
n Minute
s Second

where interval is one of the string values shown in the accompanying table, number gives the number of intervals to add, and time is the date and time to which the interval is to be added. For example, the following function returns the (formatted) time twelve hours from now.

FormatDateTime(DateAdd("h", 12, Now), DateFormat.LongDate)
Twelve hours from now is 3:34:34 AM.

DateDiff() can be used to return a value giving the number of identified intervals between two times. Its general format is

DateDiff(interval, time1, time2)

where interval is a string value representing an interval type using the time values shown in the table under the DateAdd() function, and time1 and time2 are the two times between which the interval is calculated (time1 is subtracted from time2). The following example calculates the number of minutes until midnight.

DateDiff("n", TimeString, "11:59:59 PM") + 1
There are 506 minutes until midnight.

It can be a bit tricky working with times because of the roll-over that takes place at midnight. If the value "00:00:00 AM" were to be used in the above example, it would produce -933 minutes, which are the number of minutes from the beginning of the current day. To get around this problem, one minute is added to the time difference until "11:59:59 PM" of the current day.

DatePart() can be used to extract a specified component of a given time. Its general format is

DatePart(part, time)

where part is a string value representing a time component using the time values shown in the table under the DateAdd() function, and time is any Date value. For example, the following function determines the current hour (24-hour clock) of the current day.

DatePart("h", Now)
The current hour of the day is 15

Hour() returns an Integer representing the hour of the day (24-hour clock). For instance, function Hour(Now) returns 15. This is the same value as returned from the function DatePart("h", Now).

Minute() returns an Integer representing the minute of the hour. For instance, function Minute(Now) returns 34. This is the same value as returned from the function DatePart("n", Now).

Second() returns an Integer representing the second of the minute. For instance, function Second(Now) returns 34. This is the same value as returned from the function DatePart("s", Now).

TimeSerial() returns a Date value representing a specified hour, minute, and second, with the date information set relative to January 1 of the year 1. Its general format is

TimeSerial(hour, minute, second)

For example, the function TimeSerial(5, 30, 45) returns 1/1/0001 5:30:45 AM. As in the case for the DateSerial() function, integer values are combined and converted into a Date type.

TimeValue() returns a Date type from a String value representing a time. This function works as a converter to a Date data type. For example, the function call TimeValue("4:35:17 PM") returns 1/1/0001 4:35:17 PM.


Some of the date and time functions appear trivial in isolation. However, you will find them crucial when you begin combining them in applications that relay on accurate reporting of and calculations involving dates and times.