如何修复服务器上的日期排序

问题描述 投票:0回答:1

我正在为我的项目编写一个API,其功能之一是对从数据库接收的数据进行排序。在我的笔记本电脑和 Swagger 上本地使用所有内容,一切都按预期工作,但是当我在服务器上运行相同的代码时,我开始遇到日期问题。排序会中断并返回空列表

我尝试用不同的方法修复它,例如格式化接收到的数据,但没有解决问题

我的代码:

public class Sort
{
    private readonly IMongoDatabase _database;
    public double sumExpense { get; private set; } = 0.0;

    public Sort()
    {
        var configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .Build();

        string? mongodbKey = configuration["Tokens:MongoDbConnection"];
        MongoClient client = new(mongodbKey);
        _database = client.GetDatabase("finances");
    }

    public async Task<BsonDocument> RunAsync(AuthData request, double ID)
    {
        var collection = _database.GetCollection<BsonDocument>("Expense");
        string format = "yyyy-MM-dd";

        if (!DateTime.TryParseExact(request.FirstDate, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime firstDateTime) ||
            !DateTime.TryParseExact(request.LastDate, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime lastDateTime))
        {
            return new BsonDocument
            {
                { "Error", "Invalid date format" }
            };
        }

        var startOfFirstDay = new DateTime(firstDateTime.Year, firstDateTime.Month, firstDateTime.Day, 0, 0, 0, DateTimeKind.Unspecified);
        var endOfLastDay = new DateTime(lastDateTime.Year, lastDateTime.Month, lastDateTime.Day, 23, 59, 59, DateTimeKind.Unspecified);

        var idFilter = Builders<BsonDocument>.Filter.Eq("User", ID);
        var dateFilter = Builders<BsonDocument>.Filter.Gte("Date", startOfFirstDay) &
                         Builders<BsonDocument>.Filter.Lte("Date", endOfLastDay);

        var combinedFilter = idFilter & dateFilter;
        var sortedByCategoryTask = AsyncSortingByCategory(collection, combinedFilter);
        var sortedByTagsTask = AsyncSortingByTegs(collection, combinedFilter);

        await Task.WhenAll(sortedByCategoryTask, sortedByTagsTask);

        var bsonDocument = new BsonDocument
        {
            { "Category", sortedByCategoryTask.Result },
            { "Tegs", sortedByTagsTask.Result }
        };

        return bsonDocument;
    }

    private async Task<BsonDocument> AsyncSortingByCategory(
        IMongoCollection<BsonDocument> collection,
        FilterDefinition<BsonDocument> filter)
    {
        var sortedData = new BsonDocument();

        var sortDefinition = Builders<BsonDocument>.Sort.Ascending("Category");
        var documents = await collection
            .Find(filter)
            .Sort(sortDefinition)
            .ToListAsync();

        foreach (var document in documents)
        {
            string categoryName = document["Category"].AsString;
            double sum = document["Sum"] switch
            {
                BsonDouble bsonDouble => bsonDouble.Value,
                BsonInt64 bsonInt64 => bsonInt64.Value,
                BsonDecimal128 bsonDecimal => (double)bsonDecimal.Value,
                _ => Convert.ToDouble(document["Sum"])
            };

            if (!sortedData.Contains(categoryName))
            {
                sortedData[categoryName] = new BsonArray();
            }

            sumExpense += sum;
            var array = sortedData[categoryName].AsBsonArray;
            array.Add(document);
        }

        return sortedData;
    }

    private async Task<BsonDocument> AsyncSortingByTegs(
        IMongoCollection<BsonDocument> collection,
        FilterDefinition<BsonDocument> filter)
    {
        var options = new JsonSerializerOptions
        {
            Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
            WriteIndented = true
        };

        var sortedData = new BsonDocument();
        var documents = await collection.Find(filter).ToListAsync();

        foreach (var document in documents)
        {
            if (document["Tegs"].IsBsonArray)
            {
                BsonArray tegs = document["Tegs"].AsBsonArray;

                foreach (string teg in tegs)
                {
                    if (!sortedData.Contains(teg))
                    {
                        sortedData[teg] = new BsonArray();
                    }

                    var array = sortedData[teg].AsBsonArray;
                    array.Add(document);
                }
            }
        }

        return sortedData;
    }
}
c# mongodb asp.net-web-api
1个回答
0
投票

我怀疑服务器上的区域日期/时间设置不同。

© www.soinside.com 2019 - 2024. All rights reserved.