Conversion display wrong data - c#

If i take property as string that time output will properly come but i have to do it with date and time when i convert it with date and time it will show only one record with wrong date and time what should i do any Idea.
what i done in other case it working.But when i work with registry install date it's convert it into date and time but I don't get perfect date.
controllerModel.cs
private DateTime _installedOn;
public DateTime installedon
{
get { return _installedOn; }
set
{
_installedOn = value;
RaisePropertyChanged("installedon");
}
}
ControlPanelViewModel.cs
#region Methods
public void ListedSoftware()
{
string uninstallKey = #"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(uninstallKey))
{
foreach (string skName in rk.GetSubKeyNames())
{
using (RegistryKey sk = rk.OpenSubKey(skName))
{
try
{
Controller objct = new Controller();
objct.displayname = sk.GetValue("DisplayName").ToString();
objct.displayversion = sk.GetValue("DisplayVersion").ToString();
objct.publisher = sk.GetValue("Publisher").ToString();
objct.installedon = Convert.ToDateTime(sk.GetValue("InstallDate"));
objct.estimatedSize = sk.GetValue("EstimatedSize").ToString();
Students.Add(objct);
}
catch (Exception ex)
{ }
}
}
}
}

Looking in my registry, all of the InstallDate values seem to be in the format yyyyMMdd, where yyyy is the year, MM the month and dd the day.
To parse this string format into a DateTime object, you can use the DateTime.ParseExact method:
var timestampString = sk.GetValue("InstallDate").ToString();
var timestamp = DateTime.ParseExact(timestampString, "yyyyMMdd",
CultureInfo.InvariantCulture);
Be aware that the InstallDate value may not exist in all subkeys in that part of the registry, so you will need to take that into account.

You can also use DateTime.Parse(), this one is work wor me.
CultureInfo provider = CultureInfo.InvariantCulture;
objct.installedon = DateTime.Parse(sk.GetValue("InstallDate").ToString(), provider);
Btw, I got a similar result (01010001) when sk.GetValue("InstallDate") was null.

Perhaps, Convert.ToDateTime(string) uses invalid format to parse your registry entry. You should experiment with your date format with Convert.ToDateTime(String, IFormatProvider) method. Here's good example on msdn with CultureInfo. Prehaps, CultureInfo.CurrentCulture will work for you

Related

Reading the installation date of the C# OS

With the C# Core 3.1 WinForms application, the first installation date of the operating system cannot be read through regedit. It gives different results than the date given by "SystemInfo" command with CMD.
CMD "System Info":
CMD Image
Original Install Date: 11/26/2022, 1:08:26 PM
C# Read a "Regedit InstallDate(DWord)":
Regedit Image
Date: "1.01.1601 00:02:46"
C# Read a Date
RegistryKey key = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, computerName);
key = key.OpenSubKey(#"SOFTWARE\Microsoft\Windows NT\CurrentVersion", false);
if (key != null)
{
DateTime installDate =
DateTime.FromFileTimeUtc(
Convert.ToInt64(
key.GetValue("InstallDate").ToString()));
return installDate;
}
return DateTime.MinValue;
The value in InstallDate is not a FILETIME value, but a Unix Time (seconds since 1970-01-01).
You can use
var installDate = DateTimeOffset.FromUnixTimeSeconds(regValue);
to convert to a DateTimeOffset.
For other conversion methods see How do you convert epoch time in C#?
#KlausGutter's answer is spot on, the value in the registry is a Unix time. If you want to convert it to a DateTime rather than a DateTimeOffset, then you could use something like
var installDate = DateTime.UnixEpoch.AddSeconds(regValue)
You can use this method for Converting UnixTime or whatever it is :
public static DateTime FromDate(string SerialDate)
{
var year = Convert.ToInt32(SerialDate.Substring(0, 4));
var mon = Convert.ToInt32(SerialDate[4].ToString() + SerialDate[5].ToString());
var day = Convert.ToInt32(SerialDate[6].ToString() + SerialDate[7].ToString());
try
{
var date = new DateTime(year, mon, day);
return date;
}
catch(Exception ss)
{
return DateTime.Now;
}
}

C# Check if input is valid date

I am working on a calendar. And here I want to check if the users input is a date and if it's not showing an error. I heard about DateTime.TryParse. How can I use this here properly? Can maybe anyone explain it in simple words?
public void addMeeting()
{
string readAddMeeting;
var dateFormats = new[] {"dd.MM.yyyy", "dd-MM-yyyy", "dd/MM/yyyy"}; // I copied this
Console.WriteLine("Add a schedule for specific dates: ");
readAddMeeting = Console.ReadLine();
}
Use DateTime.TryParseExact in this way:
public void addMeeting()
{
var dateFormats = new[] {"dd.MM.yyyy", "dd-MM-yyyy", "dd/MM/yyyy"};
Console.WriteLine("Add a schedule for specific dates: ");
string readAddMeeting = Console.ReadLine();
DateTime scheduleDate;
bool validDate = DateTime.TryParseExact(
readAddMeeting,
dateFormats,
DateTimeFormatInfo.InvariantInfo,
DateTimeStyles.None,
out scheduleDate);
if(validDate)
Console.WriteLine("That's a valid schedule-date: {0}", scheduleDate.ToShortDateString());
else
Console.WriteLine("Not a valid date: {0}", readAddMeeting);
}
The method returns a bool indicating whether it could be parsed or not and you pass a DateTime variable as out parameter which will be initialized if the date was valid.
Note that i'm using DateTimeFormatInfo.InvariantInfo because you don't want to use the local DateTime format but one that works in any culture. Otherwise the / in dd/MM/yyyy would be replaced with your current culture's date separators. Read
Even if it sounds a bit brutal, but it seems ike you should do some readup on arrays/lists, foreach loops and DateTime.TryParse.
That aside you have different possible date formats and want to see if one of them is valid. If we take the example from the msdn homepage for tryparse https://msdn.microsoft.com/en-us/library/ch92fbc1(v=vs.110).aspx and use foreach it becomes quite easy:
public void addMeeting()
{
string readAddMeeting;
var dateFormats = new[] {"dd.MM.yyyy", "dd-MM-yyyy", "dd/MM/yyyy"}; // I copied this
bool isDateOk = false;
Console.WriteLine("Add a schedule for specific dates: ");
readAddMeeting = Console.ReadLine();
foreach (string myDateFormat in dateFormats)
{
DateTime dateValue;
if (DateTime.TryParse(readAddMeeting, dateValue))
{
isDateOk = true;
}
}
if (isDateOk == false)
{
Console.Writeline("Sorry this is not a valid date");
}
}

How to get date only if time is 00:00:00 from DateTime c#

I want to convert DateTime object to string. What I want to achieve is following things:
Get Date only out of it if Time is 00:00:00.
Get Date and Time if both are present.
I want to achieve this using CurrentCulture.DateTimeFormat and
Convert.ToString(DateTime, IFormatProvider), otherwise I know how
to do this using .ToString() Extension method.
I have tried following things:
Thread.CurrentPrincipal = principal;
CultureInfo culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
culture.DateTimeFormat.ShortDatePattern = MPAResource.DateFormat;
culture.DateTimeFormat.LongTimePattern = "hh:mm:ss tt";
culture.DateTimeFormat.ShortTimePattern = "hh:mm:ss tt";
culture.DateTimeFormat.FullDateTimePattern = MPAResource.DateTimeFormat;
Thread.CurrentThread.CurrentCulture = culture;
Then:
string x = Convert.ToString(x.ExpectedJoiningDate, CultureInfo.CurrentCulture);
Output is 09-Oct-2015 11:00 AM. I want 09-Oct-2015 11:00 AM if time is there and 09-Oct-2015 if time is not there.
But above line gives me only date even if time is present with date.
Seems to me like this is pretty straight forward:
var dt = x.ExpectedJoiningDate;
string x = (dt.TimeOfDay == TimeSpan.Zero)?dt.ToShortDateString():dt.ToString();
PS: you can use a culture as parameter in ToString if you like. See https://msdn.microsoft.com/en-us/library/aa326720(v=vs.71).aspx for details on how to do this.
Tim made the remark that the OP wants to use Convert.ToString. It doesn't compute, so I refuse. Why doesn't it compute? Here's the code for Convert.ToString:
public static string ToString(DateTime value, IFormatProvider provider)
{
return value.ToString(provider);
}
Yes people, that's basically the same.
That said, if you're stubborn, I guess you can implement IFormatProvider in your own little class, change the format provider based on the condition, then pass that instead of the default format provider. Then, congrats, you've created a lot of senseless code that gives the exact same results using Convert.ToString.
After a while a wrote method for myself.
public static string ConvertToMyDateTimeFormat(Nullable<DateTime> value, CultureInfo IFormateProvider)
{
if (value.HasValue)
{
if (value.Value.TimeOfDay.Ticks > 0)
{
return value.Value.ToString(IFormateProvider);
}
else
{
return value.Value.ToString(IFormateProvider.DateTimeFormat.ShortDatePattern);
}
}
else
{
return string.Empty;
}
}

Datetime value with different culture not formatting correctly

I'm having a slight issue with Thread culture and getting a date to display properly.
I am overloading the ToString() method of the DateTime class.
With culture "en-CA", my date is coming out in the right format "yyyy/MM/dd"
but with culture "fr-CA", my date is coming out "yyyy-MM-dd"
I've made some unit test to display the issue.
The english test works but the french always fails.
Even if I change the GetDateInStringMethod to do .ToShortDateString. I still get the same issue.
[Test()]
public void ValidInEnglish()
{
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-CA");
Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern = Utility.DatePattern;
DateTime? currentDate = new DateTime(2009,02,7);
string expected = "2009/02/07";
string actual = DateUtils.GetDateInString(currentDate);
//This works
Assert.AreEqual(expected, actual);
}
[Test()]
public void ValidInFrench()
{
Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-CA");
Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern = Utility.DatePattern;
DateTime? currentDate = new DateTime(2009, 02, 7);
string expected = "2009/02/07";
string actual = DateUtils.GetDateInString(currentDate);
// This doesn't work
Assert.AreEqual(expected, actual);
}
public static string GetDateInString(DateTime? obj)
{
if (obj == null || !obj.HasValue)
{
return string.Empty;
}
return obj.Value.ToString(Utility.DatePattern);
}
public const string DatePattern = "yyyy/MM/dd";
Change this line:
return obj.Value.ToString(Utility.DatePattern);
to this:
return obj.Value.ToString(Utility.DatePattern, CultureInfo.InvariantCulture);
Read about it here: System.Globalization.InvariantCulture
That doesn't work because using french culture defaults the datetime formatter to use - instead of / as a separator character. If you want to keep your date the same no matter the culture then use CultureInfo.InvariantCulture if you want to use the french formatting the change your expected test result to "2009-02-07". If you are looking for more info check this msdn link.
And if you want a personal recommendation for a lib to use for dealing with the awesomeness that is Globalization then I'd recommend Noda Time.

String date time format

I am using the Vimeo API and I want to convert the string <upload_date> to a short date format, {0:d} or {0:dd/mm/yyyy}.
This is my code but it doesn't seem to be working for me.
select new VimeoVideo
{
Date = String.Format("{0:d}",(item.Element("upload_date").Value)),
};
return Vids.ToList();
}
public class VimeoVideo
{
public string Date { get; set; }
}
As Oleg suggested you can try to parse your value to DateTime and then format it (use try catch if needed). That should work (not 100% sure since I don't know what item's type is).
var myDate = DateTime.Parse(item.Element("upload_date").Value);
Date = String.Format("{0:d}", myDate);
http://msdn.microsoft.com/it-it/library/1k1skd40(v=VS.80).aspx
Just verify the type of the Value property.. The above string formatter works for System.DateTime structure.. I assume in your case its string type object. According to the given sample date time string i have written this code.. Try out this.
CultureInfo provider = CultureInfo.InvariantCulture;
var format = "yyyy-MM-dd HH:mm:ss";
var dt = DateTime.ParseExact(item.Element("upload_date").Value, format, provider);
Date = string.Format("{0:d}", dt);
Hope it works..

Categories

Resources