public DateTime EnterDeparture()
{
Console.WriteLine("Enter Year:");
return new DateTime().AddYears(int.Parse(Console.ReadLine()));
}
// This will return new DateTime(Without assigned Year) Cause DateTime is value type.
public DateTime EnterDeparture()
{
DateTime EnterDeparture = new DateTime();
Console.WriteLine("Enter Year:");
EnterDeparture.AddYears(int.Parse(Console.ReadLine()));
return EnterDeparture;
}
How to work with several fields in DateTime ? (Year,Days for example) Default constructors aren't suitable.
The DateTime.AddXXX methods return new DateTime instances, the existing struct does not change. Since each method returns a new instance, you can chain the method calls together. At the very least, you want to capture each return value into a variable. For example:
DateTime myDate = DateTime.Today;
DateTime tomorrowAtNoon = myDate.AddDays(1).AddHours(12);
You could have also written it like
DateTime tomorrow = myDate.AddDays(1);
DateTime tomorrowAtNoon = tomorrow.AddHours(12);
Follow?
Related
i have a long value then i convert the Longvalue in datetime format. I am not sure if the conversion is in the right way, but i am able to get in the right format. Now i am struggling to set the converterted datetime in groovy using setter. #formattedDate can be in date format, i do not know how to save in datetime. I get the error conversion String datetime. Please help.
def time= 1550670822 / 1000;
LocalDateTime dateTime = LocalDateTime.ofEpochSecond(time, 0, ZoneOffset.UTC);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss", Locale.ENGLISH);
String formattedDate = dateTime.format(formatter);
trial.setFinishingTime(formattedDate);
In my class i have for setFinishingTime.
public String getFinishingTime()
{
return getPropertyContainer().getString(FINISHING_TIME, "")
}
public void setFinishingTime(String finishingTime)
{
getPropertyContainer().setString(FINISHING_TIME, finishingTime)
}
This part i am not sure, should it be like this in DateTime format:
public DateTime getFinishingTime()
{
return getPropertyContainer().getDate(FINISHING_TIME, "")
}
public void setFinishingTime(DateTime finishingTime)
{
getPropertyContainer().setDate(FINISHING_TIME, finishingTime)
}
If i change this to DateTime how can i store a DateTime of dd:mm:yyyy pattern which i get from the above code. Please help
I'm using Dapper to insert and get objects to/from SQLite: one object have a property of type DateTime (and DateTimeOffset) that I have to persist and retrieve with milliseconds precision. I can't find a way to correctly retrieve the value because Dapper fail with:
System.FormatException : String was not recognized as a valid DateTime.
in System.DateTimeParse.ParseExactMultiple(String s, String[] formats, DateTimeFormatInfo dtfi, DateTimeStyles style)
in System.DateTime.ParseExact(String s, String[] formats, IFormatProvider provider, DateTimeStyles style)
in System.Data.SQLite.SQLiteConvert.ToDateTime(String dateText, SQLiteDateFormats format, DateTimeKind kind, String formatString)
in System.Data.SQLite.SQLite3.GetDateTime(SQLiteStatement stmt, Int32 index)
in System.Data.SQLite.SQLite3.GetValue(SQLiteStatement stmt, SQLiteConnectionFlags flags, Int32 index, SQLiteType typ)
in System.Data.SQLite.SQLiteDataReader.GetValue(Int32 i)
in System.Data.SQLite.SQLiteDataReader.GetValues(Object[] values)
in Dapper.SqlMapper.<>c__DisplayClass5d.<GetDapperRowDeserializer>b__5c(IDataReader r) in SqlMapper.cs: line 2587
in Dapper.SqlMapper.<QueryImpl>d__11`1.MoveNext() in SqlMapper.cs: line 1572
in System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
in System.Linq.Enumerable.ToList(IEnumerable`1 source)
in Dapper.SqlMapper.Query(IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Boolean buffered, Nullable`1 commandTimeout, Nullable`1 commandType) in SqlMapper.cs: line 1443
in Dapper.SqlMapper.Query(IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Boolean buffered, Nullable`1 commandTimeout, Nullable`1 commandType) in SqlMapper.cs: line 1382
What do I have to try? Column is of type DATETIME.
Do I have to create a custom TypeHandler and convert DateTime to and from a SQLite string in format "o"?
Dapper version 1.38
I know it's old, but I have found the solution.
After a lot of digging and analyzing Dapper code I came up with this (notice that this is 2019 year):
First you will have to create date time handler:
public class DateTimeHandler : SqlMapper.TypeHandler<DateTimeOffset>
{
private readonly TimeZoneInfo databaseTimeZone = TimeZoneInfo.Local;
public static readonly DateTimeHandler Default = new DateTimeHandler();
public DateTimeHandler()
{
}
public override DateTimeOffset Parse(object value)
{
DateTime storedDateTime;
if (value == null)
storedDateTime = DateTime.MinValue;
else
storedDateTime = (DateTime)value;
if (storedDateTime.ToUniversalTime() <= DateTimeOffset.MinValue.UtcDateTime)
return DateTimeOffset.MinValue;
else
return new DateTimeOffset(storedDateTime, databaseTimeZone.BaseUtcOffset);
}
public override void SetValue(IDbDataParameter parameter, DateTimeOffset value)
{
DateTime paramVal = value.ToOffset(this.databaseTimeZone.BaseUtcOffset).DateTime;
parameter.Value = paramVal;
}
}
Now, notice that Dapper translates .Net's type DateTimeOffset to dbType - DateTimeOffset. You need to remove this mapping and add your own like this:
SqlMapper.RemoveTypeMap(typeof(DateTimeOffset));
SqlMapper.AddTypeHandler(DateTimeHandler.Default);
That's all. Now everytime Dapper will see DateTimeOffset property in your model, it will run your DateTimeHandler to manage this.
I have found that custom TypeHandler for base types can't be used because of default typeMap that is choosen before looking for TypeHandler.
I have opened an issue dapper-dot-net but in the mean time I have solved replacing via reflection the default typeMap with a new one like the previous minus the four key DateTime, DateTime?, DateTimeOffset, DateTimeOffset?
I've made a slight modification to Adam Jachocki's solution as it didn't work for me. I am storing a date as TEXT in Sqlite and Dapper was giving me a string instead of a DateTime as the object value to parse. Apparently, Sqlite stores datetime values using three different data types: INTEGER (unix epoch), TEXT (ISO 8601 YYYY-MM-DD HH:MM:SS.SSS), and REAL ("number of days since noon in Greenwich on November 24, 4741 B.C."). That last one is really out there, so it isn't supported in the code below.
See the sqlite docs and this page for more info.
Below is my implementation of the DateTimeOffset TypeHandler. The rest of Adam's solution remains the same.
internal class DateTimeOffsetHandler : SqlMapper.TypeHandler<DateTimeOffset>
{
private static readonly TimeZoneInfo databaseTimeZone = TimeZoneInfo.Local;
private static readonly DateTime unixOrigin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
public static DateTimeOffsetHandler Default { get; } = new DateTimeOffsetHandler();
public DateTimeOffsetHandler() {}
public override DateTimeOffset Parse(object value)
{
if (!TryGetDateTime(value, out DateTime storedDateValue))
{
throw new InvalidOperationException($"Unable to parse value {value} as DateTimeOffset");
}
if (storedDateValue.ToUniversalTime() <= DateTimeOffset.MinValue.UtcDateTime)
{
return DateTimeOffset.MinValue;
}
else
{
return new DateTimeOffset(storedDateValue, databaseTimeZone.BaseUtcOffset);
}
}
public override void SetValue(IDbDataParameter parameter, DateTimeOffset value)
{
DateTime paramVal = value.ToOffset(databaseTimeZone.BaseUtcOffset).DateTime;
parameter.Value = paramVal;
}
private bool TryGetDateTime(object value, out DateTime dateTimeValue)
{
dateTimeValue = default;
if (value is DateTime d)
{
dateTimeValue = d;
return true;
}
if (value is string v)
{
dateTimeValue = DateTime.Parse(v);
return true;
}
if (long.TryParse(value?.ToString() ?? string.Empty, out long l))
{
dateTimeValue = unixOrigin.AddSeconds(l);
return true;
}
if (float.TryParse(value?.ToString() ?? string.Empty, out float f))
{
throw new InvalidOperationException("Unsupported Sqlite datetime type, REAL.");
}
return false;
}
}
I create a function. Where date can be selected by the user . And when the user not select the date i want to pass null .
public DataSet GetInvoicebyPaging(int pageIndex, int pageSize, Int32 clientId, DateTime startDate, DateTime endDate, string invoiceNumber, ref int totalInvoice)
{
// doing something here
}
And this is the code part where i am calling the function
_orderDAC.GetInvoicebyPaging(pageIndex, grdInvoice.PageSize, clientid, Convert.ToDateTime(txtFirstDate.Text.Trim()), Convert.ToDateTime(txtLastDate.Text.Trim()), txtInvoiceNumber.Text.Trim(), ref invoicecount);
Sometime the user cant fill the txtFirstDate.Text but i am converting Convert.TodateTime() so how can i fix this because when user not fill the datetime it give me exception. So how can i handle this .
You need to change your method to:
public DataSet GetInvoicebyPaging(int pageIndex, int pageSize, Int32 clientId, DateTime? startDate, DateTime endDate, string invoiceNumber, ref int totalInvoice)
{
// doing something here
}
And when you parse the user data you can do:
DateTime? start = null;
DateTime possibleStartValue;
if(!string.IsNullOrEmpty(txtTextBox.Text) && DateTime.TryParse(txtTextBox.Text, out possibleStartValue))
{
start = possibleStartValue;
}
You can create a nullable date time variable as follows
DateTime? value = null;
and pass as a parameter
In your function you can use like DateTime? value as parameter
So you will have to do the following step
DateTime? startDate=txtFirstDate.Text.Trim()==""?null:Convert.ToDateTime(txtFirstDate.Text.Trim());
change your function argument so that it can take null value as above.
For any dates you want to be able to accept as null, like DateTime startDate you need to make them nullable like DateTime? startDate
And then before you call GetInvoicebyPaging try and sort out the datetimes.
DateTime startDate;
var correctStart = DateTime.TryParse(txtFirstDate.Text.Trim(), out startDate);
And then pass the parameter like
_orderDAC.GetInvoicebyPaging(pageIndex, grdInvoice.PageSize,
clientid, (correctStart ? startDate : null), etc
And you may have to check if txtFirstDate.Text is null as well.
After declaring startDate above you can do:
var dateString = txtFirstDate.Text ?? "";
And pass dateString.Trim() into the DateTime.TryParse
public DateTime EnterDeparture()
{
DateTime EnterDeparture = new DateTime();
Console.WriteLine("Enter Year:");
EnterDeparture.AddYears(int.Parse(Console.ReadLine()));
return EnterDeparture;
}
Train train = new Train(number, EnterDeparture()); //Train takes DateTime (2nd parameter)
Console.WriteLine(Convert.ToString(train.Departure));
Rusult in console always the same.
What is wrong?
How to declare DateTime in class Train right?
DateTime.AddYears() returns a new DateTime rather than modify the one you call the method on.
You need to return that new DateTime, not the old one:
public DateTime EnterDeparture()
{
Console.WriteLine("Enter Year:");
return new DateTime().AddYears(int.Parse(Console.ReadLine()));
}
Our database has all times stored as UTC, and we know the user's current timezone, so want to return it relative to that. So we want to incorporate the offset in a LINQ projection as so:
var users = from u in this.Context.Users
select new UserWithCorrectedDate
{
Id = u.Id,
FirstName = u.FirstName,
LastName = u.LastName,
RegistrationDate = u.RegistrationDate.Value.AddHours(-5)
};
Of course, Linq2EF cannot convert "AddHours" into a canonical function. Is there another way to do this?
UPDATE:
Another thought, if the timezone offset was stored in the database as another column, would there be a way to have the DB perform the calculation (date + offset)?
Linq to Entities supports SqlFunctions. If you know the offset number of hours you could do something like this:
var users = from u in this.Context.Users
select new UserWithCorrectedDate
{
Id = u.Id,
FirstName = u.FirstName,
LastName = u.LastName,
RegistrationDate = SqlFunctions.DateAdd("hour", -5, u.RegistrationDate.Value)
};
If you want to be more precise by using the Timezone function, you could do something like this (this is a bit of a workaround):
public static DateTime UtcToNewYorkTime(DateTime utcDateTime)
{
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
DateTime converted = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, tzi);
return converted;
}
And then in your POCO UserWithCorrectedDate object, have a get only property for the Timezoned date ie.
public class UserWithCorrectDate
{
public DateTime UTCDate {get;set;}
public DateTime NYDate
{
get
{
return Utilities.UtcToNewYorkTime(this.UTCDate);
}
}
}
The quick and dirty way to do this is to convert to a list, and just linq to object to get it done:
from u in this.Context.Users.ToList()
select new { ... }