Date
methods:-
- These are used to manipulate the date & time values.
- These are available in 'System.DateTime'
Steps:
1.
Declare
DateTime variable:
DateTime dt1;
2.
Assign
date and time into the variable:
dt1
= System.Convert.ToDateTime("9/7/2013 8:30 pm");
Date
format to follow: mm/dd/yyyy hh:mi:ss
am/pm
(US
date format)
3.
Assign
system date & time:
dt1
= DateTime.Now;
4.
Get
independent values:
dt1.Day Ex:
12
dt1.Month Ex:
4
dt1.Year Ex: 2013
dt1.Hour Ex: 15
(24-hours format)
dt1.Minute Ex:
23
dt1.Second Ex: 25
dt1.MilliSecond Ex:
340
5.
Get
long & short dates:
dt1.ToLongDateString()
o/p: Friday, April 12, 2013
dt1.ToShortDateString()
o/p: 4/12/2013
6.
Get
long & short time:
dt1.ToLongTimeString()
o/p: 3:26:20 PM
dt1.ToShortTimeString()
o/p: 3:26 PM
7.
Get
date difference:
dt1
- dt2
8.
Get
today's index in the year: (among 0 to
365)
dt1.DayOfYear
9.
Get
week name:
dt1.DayOfWeek
o/p: Friday
10. Find out no. of days in the month:
DateTime.DaysInMonth(int
year, int month);
Ex:-
Develop
a c# console app to calculate age of the person.
using
System;
namespace
AgeCalculator
{
class Program
{
static void Main(string[] args)
{
//declare variables
DateTime
dt1, dt2;
//capture system date & time
dt1 = DateTime.Now;
//accept dob
Console.WriteLine("Your date of birth (mm/dd/yyyy): ");
dt2 = Convert.ToDateTime(Console.ReadLine());
//calc age
double age = (dt1 - dt2).TotalDays / 365;
age = Math.Round(age, 1); //optional
Console.WriteLine("Your age is " + age);
Console.ReadKey();
}
}
}
//press
F5 to run
Ex:-
Develop
a c# console app to print system date & time in various formats.
using
System;
namespace
PrintingDatesDemo
{
class Program
{
static void Main(string[] args)
{
//declare variable
DateTime dt1;
//capture system date & time
dt1 = DateTime.Now;
//print in variety formats
Console.WriteLine(dt1);
Console.WriteLine(dt1.ToString());
//universal format
//british
format
Console.WriteLine(dt1.Day + "-" + dt1.Month + "-" + dt1.Year);
//indian format
Console.WriteLine(dt1.Day + "/" + dt1.Month + "/" + dt1.Year); Console.WriteLine(dt1.ToLongDateString());
Console.WriteLine(dt1.ToShortDateString());
Console.WriteLine(dt1.ToLongTimeString());
Console.WriteLine(dt1.ToShortTimeString());
Console.WriteLine(dt1.DayOfYear);
Console.WriteLine(dt1.DayOfWeek);
Console.ReadKey();
}
}
}
//press
f5 to run
No comments:
Post a Comment