How do you get the current time of day?
Asked Answered
A

21

315

How do you get the current time (not date AND time)?

Example: 5:42:12 PM

Alli answered 17/11, 2008 at 21:6 Comment(0)
S
436

DateTime.Now.TimeOfDay gives it to you as a TimeSpan (from midnight).

DateTime.Now.ToString("h:mm:ss tt") gives it to you as a string.

DateTime reference: https://msdn.microsoft.com/en-us/library/system.datetime

Skatole answered 17/11, 2008 at 21:8 Comment(4)
DateTime.Now.ToShortTimeString() does the same as the second suggestion.Hospital
well, almost the same, it returns a string but is missing the seconds portion of the time.Hospital
.ToString("HH:mm:ss tt") would give you 17:42:12 PM, while .ToString("h:mm:ss tt") gives you 5:42:12 PM.Millenary
@Kyle - not quite accurate. ToShortTimeString returns the time in the user's selected short time format, as specified in the region settings of Windows.Bathrobe
G
62

Try this:

DateTime.Now.ToString("HH:mm:ss tt");

For other formats, you can check this site: C# DateTime Format

Gemeinschaft answered 2/4, 2012 at 10:20 Comment(0)
D
47

Another option using String.Format()

string.Format("{0:HH:mm:ss tt}", DateTime.Now)
Dire answered 18/11, 2008 at 2:7 Comment(0)
O
28

Current time with AM/PM designator:

DateTime.Now.ToString("hh:mm:ss tt", System.Globalization.DateTimeFormatInfo.InvariantInfo)
DateTime.Now.ToString("hh:mm:ss.fff tt", System.Globalization.DateTimeFormatInfo.InvariantInfo)

Current time using 0-23 hour notation:

DateTime.Now.ToString("HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo)
DateTime.Now.ToString("HH:mm:ss.fff", System.Globalization.DateTimeFormatInfo.InvariantInfo)
Oringa answered 17/11, 2008 at 21:15 Comment(2)
After reading the question again, I think you are not wrong. But I am not wrong either because if this is a general question as you propose, then most of the answerers have misunderstood the question since their answers are not general but specific. All in all, I think the question could have been much clearer. By the way, what does "I undid your -1's" mean?Bedrock
Had there not be any misundestandings they would have put all versions not something that comes first on mind. We all know that SO is very generous to people who try hard to answer. But yeah, let's not deviate from the topic much. All I can say is that I will review all my -1's and decide again.Bedrock
W
25
DateTime.Now.TimeOfDay

or

DateTime.Now.ToShortTimeString()
Wooldridge answered 17/11, 2008 at 21:10 Comment(0)
C
18
DateTime.Now.ToString("yyyy-MM-dd h:mm:ss tt");

just Try It's use full to your Need

Cohosh answered 11/12, 2017 at 13:22 Comment(0)
Z
17

Here we go:

 DateTime time = DateTime.Now;
 Console.WriteLine(time.ToString("h:mm:ss tt"));
Zoologist answered 22/10, 2015 at 19:57 Comment(1)
The t in time should be capitalized. Fixed it for your.Inculcate
I
14

This will be better, Try This one

    DateTime.Now.ToShortTimeString();

For this you don't need to specify the Format for the Time.

Ingratitude answered 17/5, 2012 at 4:35 Comment(0)
A
13

Datetime.TimeOfDay returns a TimeSpan and might be what you are looking for.

Almonry answered 17/11, 2008 at 21:9 Comment(0)
L
8

Get the current date and time, then just use the time portion of it. Look at the possibilities for formatting a date time string in the MSDN docs.

Leuctra answered 17/11, 2008 at 21:8 Comment(0)
A
7

I think this code will solve your problem

DateTime.Now.ToString("HH:mm")
Allynallys answered 8/10, 2020 at 13:20 Comment(1)
The ToString method has already been covered by several other solutions. In addition, this also does not capture seconds or AM/PM time.Gujarati
E
6

This can be a possible solution:

DateTime now = DateTime.Now;
string time = now.ToString("T");
Eventide answered 15/1, 2014 at 18:59 Comment(0)
M
4
var CurDate= DateTime.Now;
CurDate.Hour;
CurDate.Minute;
CurDate.Millisecond
Mountebank answered 2/1, 2017 at 6:55 Comment(0)
I
3

To calculate the current datetime:

DateTime theDate = DateTime.UtcNow;

string custom = theDate.ToString("d");

MessageBox.Show(custom);
Intort answered 3/2, 2012 at 9:22 Comment(0)
B
3
MyEmail.Body = string.Format("The validation is done at {0:HH:mm:ss} Hrs.",DateTime.Now);

Can Use {0:HH:mm:ss}, {0:HH:mm:ss.fff}, {0:DD/mm/yyy HH:mm:ss}, etc...

Brazier answered 15/1, 2014 at 18:45 Comment(0)
K
3

I'm experimenting with this also and find these pages helpful as well. First the main class... https://msdn.microsoft.com/en-us/library/system.datetime(v=vs.110).aspx

Now some specifier formats for the ToString method... https://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo(v=vs.110).aspx

Example:

using System;

namespace JD
{
    class Program
    {
        public static DateTime get_UTCNow()
        {
            DateTime UTCNow = DateTime.UtcNow;
            int year = UTCNow.Year;
            int month = UTCNow.Month;
            int day = UTCNow.Day;
            int hour = UTCNow.Hour;
            int min = UTCNow.Minute;
            int sec = UTCNow.Second;
            DateTime datetime = new DateTime(year, month, day, hour, min, sec);
            return datetime;
        }

        static void Main(string[] args)
        {
            DateTime datetime = get_UTCNow();            

            string time_UTC = datetime.TimeOfDay.ToString();
            Console.WriteLine(time_UTC);

            Console.ReadLine();

        }
    }
}

I threw that TimeOfDay method in there just to show that you get a default of 24 hour time as is stated "the time from midnight"

You may use my geter method(); :-D

Knott answered 24/9, 2016 at 18:54 Comment(0)
M
2

This will show you only the current time, in 24 hour format:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(DateTime.Now.ToLongTimeString().ToString());
        Console.WriteLine(DateTime.Now.ToShortTimeString().ToString());
        Console.ReadLine();
    }
}

Regards
K

Molotov answered 17/11, 2008 at 21:16 Comment(1)
no need to use ToString() on strings :DIal
A
2

very simple DateTime.Now.ToString("hh:mm:ss tt")

Acquittance answered 4/1, 2014 at 17:53 Comment(0)
P
2

Use the code below

DateTime.Now.ToString("h:mm:ss tt")
Prairial answered 25/2, 2020 at 12:42 Comment(1)
How does this differ from the highest voted answer?Toothwort
S
0

In my case I have used the below code to get time alone from DateTime.

var currentDateTime = DateTime.Now; 
var currentTimeAlone = new TimeSpan(currentDateTime.Hour, currentDateTime.Minute,    currentDateTime.Second); 
Console.WriteLine(currentTimeAlone);

Hope it helps for someone. :)

Salazar answered 2/5, 2021 at 7:2 Comment(0)
C
-7

Try this one. Its working for me in 3tier Architecture Web Application.

"'" + DateTime.Now.ToString() + "'"

Please remember the Single Quotes in the insert Query.

For example:

string Command = @"Insert Into CONFIG_USERS(smallint_empID,smallint_userID,str_username,str_pwd,str_secquestion,str_secanswer,tinyint_roleID,str_phone,str_email,Dt_createdOn,Dt_modifiedOn) values ("
 + u.Employees + ","
 + u.UserID + ",'"
 + u.Username + "','"
 + u.GetPassword() + "','"
 + u.SecQ + "','"
 + u.SecA + "',"
 + u.RoleID + ",'"
 + u.Phone + "','"
 + u.Email + "','"
 + DateTime.Now.ToString() + "','"
 + DateTime.Now.ToString() + "')";

The DateTime insertion at the end of the line.

Calabash answered 17/11, 2008 at 21:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.