view src/core/time.cc @ 258:862d0d8619f6

*: HUUUGE changes animia has been renamed to animone, so instead of thinking of a health condition, you think of a beautiful flower :) I've also edited some of the code for animone, but I have no idea if it even works or not because I don't have a mac or windows machine lying around. whoops! ... anyway, all of the changes divergent from Anisthesia are now licensed under BSD. it's possible that I could even rewrite most of the code to where I don't even have to keep the MIT license, but that's thinking too far into the future I've been slacking off on implementing the anime seasons page, mostly out of laziness. I think I'd have to create another db file specifically for the seasons anyway, this code is being pushed *primarily* because the hard drive it's on is failing! yay :)
author Paper <paper@paper.us.eu.org>
date Mon, 01 Apr 2024 02:43:44 -0400
parents 7cf53145de11
children 91ac90a34003
line wrap: on
line source

#include "core/time.h"
#include "core/strings.h"

#include <cassert>
#include <cmath>
#include <cstdint>
#include <ctime>
#include <string>

namespace Time {

Duration::Duration(int64_t l) {
	length = l;
}

std::string Duration::AsRelativeString() {
	std::string result;

	auto get = [](int64_t val, const std::string& s, const std::string& p) {
		return Strings::ToUtf8String(val) + " " + (val == 1 ? s : p);
	};

	if (InSeconds() < 60)
		result = get(InSeconds(), "second", "seconds");
	else if (InMinutes() < 60)
		result = get(InMinutes(), "minute", "minutes");
	else if (InHours() < 24)
		result = get(InHours(), "hour", "hours");
	else if (InDays() < 28)
		result = get(InDays(), "day", "days");
	else if (InDays() < 365)
		result = get(InDays() / 30, "month", "months");
	else
		result = get(InDays() / 365, "year", "years");

	if (length < 0)
		result = "In " + result;
	else
		result += " ago";

	return result;
}

int64_t Duration::InSeconds() {
	return length;
}

int64_t Duration::InMinutes() {
	return std::llround(static_cast<double>(length) / 60.0);
}

int64_t Duration::InHours() {
	return std::llround(static_cast<double>(length) / 3600.0);
}

int64_t Duration::InDays() {
	return std::llround(static_cast<double>(length) / 86400.0);
}

int64_t GetSystemTime() {
	static_assert(sizeof(int64_t) >= sizeof(time_t));
	time_t t = std::time(nullptr);
	return *reinterpret_cast<int64_t*>(&t);
}

} // namespace Time