I have this simple time program that uses DateTime.Now
, it part of a bigger program I have but this is just a small error I notice. I made a TimeStamp string to get the time of whenever something was done in the code and sending to the console. However, its not updating? I swear at one point it did work and was updating but then it stopped, am I missing something?
p.s I dont need the seconds but I put it there for testing purposes, I have also tried it with DateTime.UtcNow
and it still didn't work
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1TimeStampNEW
{
internal class Program
{
private static DateTime Now = DateTime.Now;
static string strDate = Now.ToString("MM/dd/yyyy");
static string timeString = DateTime.Now.ToString("hh:mm ss tt");
static string TIMESTAMP = strDate " " timeString " ";
static void Main(string[] args)
{
char input;
do
{
Console.WriteLine("\n" TIMESTAMP);
Console.WriteLine("\nWould you like to repeat? Y/N");
input = Convert.ToChar(Console.ReadLine());
}
while (input == 'y');
Console.WriteLine("\nPress any key to exit.");
Console.ReadKey();
}
}
}
Output
08/30/2022 12:57 58 PM
Would you like to repeat? Y/N
y
08/30/2022 12:57 58 PM
Would you like to repeat? Y/N
CodePudding user response:
TIMESTAMP
is just a string. Once you set it, there is no relationship to the DateTime
type.
You want something more like this:
do
{
Console.WriteLine($"\n{DateTime.Now:MM/dd/yyyy hh:mm:ss tt}");
Console.WriteLine("\nWould you like to repeat? Y/N");
input = Console.ReadLine()[0];
}
while (input == 'y');
If you want a string value formatted a certain way every time you use it, one way is via a property:
public string TIMESTAMP {get { return DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt"); } }
Of course, this needs to be in a class somewhere, but then you could use it like this, which looks more like the original code:
do
{
Console.WriteLine($"\n" myClass.TIMESTAMP);
Console.WriteLine("\nWould you like to repeat? Y/N");
input = Console.ReadLine()[0];
}
while (input == 'y');
And of course, a method can do the same thing, but for some reason this just feels like a property fits more what you are trying to do.
CodePudding user response:
Try something like this
public string TIMESTAMP {get {return DateTime.Now.ToString();} };
Every time you use TIMESTAMP it will get the current date and time and return it as a string.