I'm facing an issue with date formatting. Upon calling up the UpdateItem action, the date format for CreatedAt gets messed up. I'm using JSON by the way, so must be something to do with date serialization.
Model:
public class Item
{
public int ItemId { get; set; }
public string ItemName { get; set; }
public string CreatedBy { get; set; }
public DateTime? CreatedAt { get; set; }
public string UpdatedBy { get; set; }
public DateTime? UpdatedAt { get; set; }
}
Create action:
public int CreateItem(Item item)
{
var item = new Item();
viewModel.CopyToItem(item);
item.CreatedBy = WebSecurity.CurrentUserName;
item.CreatedAt = DateTime.Now;
db.Items.Add(item);
db.SaveChanges();
return item.ItemId;
}
Update action:
public void UpdateItem(Item item)
{
item.UpdatedBy = WebSecurity.CurrentUserName;
item.UpdatedAt = DateTime.Now;
db.SaveChanges();
}
The incorrect date format:
/Date(1395366469723)/
It should be:
2014-03-21T09:50:01.747
I tried this in the controller but get a String was not recognized as a valid DateTime' error.
string isoJson = JsonConvert.SerializeObject(DateTime.Now, new IsoDateTimeConverter());
item.CreatedAt = DateTime.ParseExact(isoJson, "yyyy-MM-dd hh:mm:ss.ttt", CultureInfo.InvariantCulture);
Using non-nullable DateTime in the model didn't fix it either.
Javascript uses Unix Time. If you are wanting to get a DateTime object with the given javascript date value, create a new DateTime object from 1/1/1970 and then add the milliseconds.
Observe:
var dt = new DateTime(1970, 1, 1).AddMilliseconds(1395366469723);
// "21/03/2014 1:47:49 AM"
Related
I have a params which contains a start date and end date and then use it to query, but I wanted to handle that even if there is no start and enddate, it will will query data. How do we handle that in C#?
So that if there is no startDate and endDate, then it will just proceed on the query.
The filteredData variable is the query. The issue right now is that when there is no startDate and endDate it will not query the data, so the solution if to handle date range if it has no value. Any idea guys? Thanks.
#code snippet
public async Task<IPagedList<TransactionListDto>> GetList(DateTime? startDate , DateTime? endDatestring status, int id, string sortKey, string sortOrder, string searchString, int page, int pageSize, string transactionType, string repmFilter, string transactionSubType, string masterBrokerCompany, string masterBrokerName)
{
var sortKeys = JsonConvert.DeserializeObject<List<string>>(sortKey);
var sortOrders = JsonConvert.DeserializeObject<List<string>>(sortOrder);
List<string> statusValues = new List<string>();
List<string> transactionTypeValues = new List<string>();
if (!string.IsNullOrEmpty(status))
{
statusValues = status.Split(',').ToList();
}
if (!string.IsNullOrEmpty(transactionType))
{
transactionTypeValues = transactionType.Split(',').ToList();
}
.......
var filteredData = mappedData.Where(x => (masterBrokerCompanyValues.Count == 0 || masterBrokerCompanyValues.Contains(x.MasterBrokerCompany)) && x.TargetCompletionDate >= startDate && endDate <= x.TargetCompletionDate);
var paginatedData = await AppUtil.MultipleSort<TransactionListDto>(
filteredData.AsQueryable(), sortKeys, sortOrders).ToPagedListAsync(page, pageSize);
The short answer for what you want is to make those optional parameters:
public async Task<IPagedList<TransactionListDto>> GetList(string status, int id, string sortKey, string sortOrder, string searchString, int page, int pageSize, string transactionType, string repmFilter, string transactionSubType, string masterBrokerCompany, string masterBrokerName, DateTime? startDate = null, DateTime? endDate = null)
Note: they have to be moved to the end.
The better answer is to consolidate all your parameters into a Filter class, as it appears you are using them as filters. This will allow more of them to become optional as well.
public class Filter {
public string status { get; set; }
public int id { get; set; }
public string sortKey { get; set; }
public string sortOrder { get; set; }
public string searchString { get; set; }
public int page { get; set; }
public int pageSize { get; set; }
public string transactionType { get; set; }
public string repmFilter { get; set; }
public string transactionSubType { get; set; }
public string masterBrokerCompany { get; set; }
public string masterBrokerName { get; set; }
public DateTime? startDate { get; set; }
public DateTime? endDate { get; set; }
}
public async Task<IPagedList<TransactionListDto>> GetList(Filter filter) {
...
}
The great thing about the Filter class is that if it's coming from your action method in MVC for example, your signature can change in the exact same way and it will just work.
Just replace your potential null values by something that won't be limiting :
Datetime startDateForFilter = startDate ?? Datetime.Min;
Datetime endDateForFilter = endDate ?? Datetime.Max;
If I understand your problem correctly, if startDate and endDate are not given, your query returns an empty list.
It's probably because when you create instance of Datetime, it is automatically initialized to default value. That means, that both values are same. Try to find lowest possible date and highest possible date and set them when initialized.
Datetime startDate = DateTime.MinValue;
Datetime endDate= DateTime.MaxValue;
I'm trying to create a filter and find records by a date range. The thing is, the dates in our mongo server are (sadly, its historically like this and was imported from another database) stored as string type, in the format of "dd/MM/yyyy hh:mm:ss". How can I filter from user input dates? No matter what I've tried I got wrong results.
Here's some code:
[Serializable]
public class Error
{
[BsonElement("projectName")]
public string projectName { get; set; }
[BsonElement("programName")]
public string programName { get; set; }
[BsonElement("errorDescription")]
public string errorDescription { get; set; }
[BsonElement("userDescription")]
public string userDescription { get; set; }
[BsonElement("logDateTime")]
[BsonSerializer(typeof(DateSerializer))]
public DateTime logDateTime { get; set; }
[BsonElement("writeDateTime")]
public string writeDateTime { get; set; }
}
And here's the DateSerializer:
public class DateSerializer: SerializerBase<DateTime>
{
public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, DateTime value)
{
context.Writer.WriteString(value.ToString(CultureInfo.InvariantCulture));
}
public override DateTime Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
{
var dateText = context.Reader.ReadString();
return convertToDate(dateText);
}
private DateTime convertToDate(string dateText)
{
CultureInfo ci = new CultureInfo(CultureInfo.CurrentCulture.Name);
ci.DateTimeFormat.ShortDatePattern = "dd'/'MM'/'yyyy";
ci.DateTimeFormat.LongTimePattern = "hh':'mm tt";
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
string format = "dd/MM/yyyy HH:mm:ss";
DateTime dateTime = DateTime.ParseExact(dateText, format, ci);
return dateTime;
}
}
on my filter:
DateTime dateTime2 = DateTime.ParseExact(date, format, ci);
var fromDateFilter = builder.Gte(x => x.error.logDateTime, dateTime2);
and eventually:
filter = filter & fromDateFilter;
var results = errorCollection.Find(filter).ToList();
I've tried many different ways but can't seem to get the comparison to work properly.
Edit: I only care about the dates. The time is not very important.
Edit 2 - Apparently it only compares the day, for example it returns that 01/06/2017 (dd/mm/yyyy) is smaller than 06/02/2017 (dd/mm/yyyy). This is also true for 02-05/06/2017 until 06/06/2017.
In my C# console application project I'm using MongoDB.Driver.2.4.3 with connection to MongoDB 3.2.10.
How would I convert "playerInBrazil.birthdate" in my code which is defined as BsonDateTime (I believe this is in UTC) to my local datetime value (Eastern Standard Time)?
I was trying to do subtract operation(not allowed) and DateTime.ToLocalTime Method () but couldn't make it work.
static void Main(string[] args)
{
DateTime myTimeConvert = DateTime.Now;
var client = new MongoClient("mongodb://localhost:27017");
var DB = client.GetDatabase("football");
var players = DB.GetCollection<Player>("players");
var playersInBrazil = players.AsQueryable()
.Where(p => p.country == "Brazil");
foreach (var playerInBrazil in playersInBrazil)
{
Console.Write(playerInBrazil.firstname);
Console.Write(" birthdate in UTC time is ");
Console.Write(playerInBrazil.birthdate);
Console.Write(" and in my local time is ");
//myTimeConvert =?
Console.WriteLine(myTimeConvert);
}
}
internal class Player
{
public ObjectId Id { get; set; }
public string firstname { get; set; }
public BsonDateTime birthdate { get; set; }
public string country { get; set; }
public double goals { get; set; }
}
}
BsonDateTime has a .ToLocalTime() method that returns a DateTime
More info here http://api.mongodb.com/csharp/current/html/M_MongoDB_Bson_BsonDateTime_ToLocalTime.htm
Say I have 2 classes with the same set of properties:
public class MyDto
{
public int Id { get; set; }
public DateTime CreatedOn { get; set; }
}
public class MyViewModel
{
public int Id { get; set; }
public DateTime CreatedOn { get; set; }
}
I want to map with AutoMapper, adjusting the UTC date of the input class to local time of the output class, e.g., granted I am in UK where UTC offset currently is 1h:
var input = new MyDto {Id = 1, CreatedOn = DateTime.Parse("01-01-2015 14:30")};
var output = Mapper.Map<MyViewModel>(input); // output.CreatedOn = "01-01-2015 15:30"
Can I cofigure AutoMapper to this automatically for all DateTime properties?
N.B. to adjust the time I use DateTime.SpecifyKind(value, DateTimeKind.Utc)
You can create a custom type converter:
public class CustomDateTimeConverter : ITypeConverter<DateTime, DateTime> {
public DateTime Convert(ResolutionContext context) {
var inputDate = (DateTime) context.SourceValue;
var timeInUtc = DateTime.SpecifyKind(inputDate, DateTimeKind.Utc);
return TimeZoneInfo.ConvertTime(timeInUtc, TimeZoneInfo.Local);
}
}
This will make AutoMapper perform the conversion from UTC to local time for every mapping between two DateTime properties.
I am using Entity Framework to insert a row of data into my Application table.
Here's the class:
public partial class Application
{
public Application()
{
this.TestAccounts = new List<TestAccount>();
}
public int ApplicationId { get; set; }
public string Name { get; set; }
public byte[] RowVersion { get; set; }
public System.DateTime ModifiedDate { get; set; }
public virtual ICollection<TestAccount> TestAccounts { get; set; }
}
Here's the C# code:
_Uow.Applications.Add(new Application { Name = name });
It's giving me an error saying
InnerException: System.Data.UpdateException
HResult=-2146233087
Message=An error occurred while updating the entries. See the inner exception for details.
Source=System.Data.Entity
InnerException: System.Data.SqlClient.SqlException
HResult=-2146232060
Message=The conversion of a datetime2 data type to a datetime data type
resulted in an out-of-range value.
How can I change my C# code to insert the current date in the ModifiedDate field?
You could specify a new constructor
public Application(string Name)
{
if(ModifiedDate == null)
//ModifiedDate = Convert.ToDateTime(01.01.2000);
ModifiedDate = DateTime.Now;
}
OR
public Application(string Name, System.Nullable<DateTime> modifiedDate)
{
if(modifiedDate != null)
//ModifiedDate = Convert.ToDateTime(01.01.2000);
ModifiedDate = DateTime.Now;
else
Do stuff
}
This isn't beatifull, but should do the trick.
Simply that way:
_Uow.Applications.Add(new Application
{
Name = name,
ModifiedDate = DateTime.Now
});
Or you may do it in the constructor:
public class Application
{
public Application()
{
ModifiedDate = DateTime.Now;
}
}
By the way: You got the exception because per default c# DateTime is more precise than datetime of SQL. Like the message says: Use datetime2 in SQL. DateTime has it's min value as initial value, which is too low for SQL datetime.
hi your ModifiedDate is initialized with minvalue as a result it gives an exception. Better to use either
public System.DateTime? ModifiedDate { get; set; } to make it nullable or
initialize in the construction
public Application()
{
this.TestAccounts = new List<TestAccount>();
ModifiedDate = DateTime.Now;
}