Reputation: 1
DateTime waktu;
if(item.waktu.Length>=8)
{
try
{
long binary = BitConverter.ToInt64(item.waktu, 0);
waktu = DateTime.FromBinary(binary);
Console.WriteLine($"Converted DateTime :{waktu}");
if (waktu.Year <1900 || waktu.Year >DateTime.Now.Year+1)
{
throw new ArgumentOutOfRangeException("Datetime value is out of range.");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error Converting Timestamp:{ex.Message}");
waktu = DateTime.MinValue;
}
}
else
{
Console.WriteLine("Invalid Timestamp length.");
waktu = DateTime.MinValue;
}
string tampilwaktu = waktu.ToString("dd/MM/yyyy HH:mm");
dataGridView1.Rows.Add(item.id_log, item.tb_user.Username, tampilwaktu, item.aktivitas);
I want to display in the form ("dd/MM/yyyy HH:mm") but it doesn't happen and instead displays ("01/01/0001 01:01"), what should I do?
Upvotes: 0
Views: 41
Reputation: 1
The Waktu variable is being assigned the date/time variable
Ensure item.waktu
is exactly 8 bytes before conversion
Validate the output of BitConverter.ToInt64 before using it
Print debug information to check if item.waktu
is valid
Some causes for the error might be from the following
Invalid Binary Data
If item.waktu is not a valid binary timestamp, BitConverter.ToInt64(item.waktu, 0) will produce incorrect values.
Array Length Mismatch
item.waktu.Length
should be exactly 8 bytes for BitConverter.ToInt64 to work correctly. Otherwise, an exception might occur, leading toDateTime.MinValue
being assigned.
Out-of-Range Date Values
If waktu.Year < 1900 || waktu.Year > DateTime.Now.Year + 1, an exception is thrown, and waktu is assigned DateTime.MinValue.
Exception Handling Any exception (e.g.,
ArgumentOutOfRangeException, FormatException) causes waktu = DateTime.MinValue.
DateTime waktu;
if (item.waktu != null && item.waktu.Length == 8) // Ensure correct length
{
try
{
long binary = BitConverter.ToInt64(item.waktu, 0);
waktu = DateTime.FromBinary(binary);
if (waktu.Year < 1900 || waktu.Year > DateTime.Now.Year + 1)
{
throw new ArgumentOutOfRangeException("Datetime value is out of range.");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error Converting Timestamp: {ex.Message}");
waktu = DateTime.Now; // Assign current time instead of MinValue
}
}
else
{
Console.WriteLine("Invalid Timestamp length.");
waktu = DateTime.Now; // Assign current time instead of MinValue
}
// Format the DateTime correctly
string tampilwaktu = waktu.ToString("dd/MM/yyyy HH:mm");
// Add row to DataGridView
dataGridView1.Rows.Add(item.id_log, item.tb_user.Username, tampilwaktu, item.aktivitas);
Upvotes: 0