How do I express a date type in TypeScript? - date

How do I express dates in TypeScript? Dates aren't a TypeScript type, so do I use any or object? Seems like there would be a "right" way to do:
let myDate: any = new Date();
I couldn't find much on Google, despite it being such a simple question.

The type is Date:
const d: Date = new Date(); // but the type can also be inferred from "new Date()" already
It is the same as with every other object instance :)

Every class or interface can be used as a type in TypeScript.
const date = new Date();
will already know about the date type definition as Date is an internal TypeScript object referenced by the DateConstructor interface.
And for the constructor you used, it is defined as:
interface DateConstructor {
new(): Date;
...
}
To make it more explicit, you can use:
const date: Date = new Date();
You might be missing the type definitions though, the Date is coming for my example from the ES6 lib, and in my tsconfig.json I have defined:
"compilerOptions": {
"target": "ES6",
"lib": [
"es6",
"dom"
],
You might adapt these settings to target your wanted version of JavaScript.
The Date is by the way an Interface from lib.es6.d.ts:
/** Enables basic storage and retrieval of dates and times. */
interface Date {
/** Returns a string representation of a date. The format of the string depends on the locale. */
toString(): string;
/** Returns a date as a string value. */
toDateString(): string;
/** Returns a time as a string value. */
toTimeString(): string;
/** Returns a value as a string value appropriate to the host environment's current locale. */
toLocaleString(): string;
/** Returns a date as a string value appropriate to the host environment's current locale. */
toLocaleDateString(): string;
/** Returns a time as a string value appropriate to the host environment's current locale. */
toLocaleTimeString(): string;
/** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */
valueOf(): number;
/** Gets the time value in milliseconds. */
getTime(): number;
/** Gets the year, using local time. */
getFullYear(): number;
/** Gets the year using Universal Coordinated Time (UTC). */
getUTCFullYear(): number;
/** Gets the month, using local time. */
getMonth(): number;
/** Gets the month of a Date object using Universal Coordinated Time (UTC). */
getUTCMonth(): number;
/** Gets the day-of-the-month, using local time. */
getDate(): number;
/** Gets the day-of-the-month, using Universal Coordinated Time (UTC). */
getUTCDate(): number;
/** Gets the day of the week, using local time. */
getDay(): number;
/** Gets the day of the week using Universal Coordinated Time (UTC). */
getUTCDay(): number;
/** Gets the hours in a date, using local time. */
getHours(): number;
/** Gets the hours value in a Date object using Universal Coordinated Time (UTC). */
getUTCHours(): number;
/** Gets the minutes of a Date object, using local time. */
getMinutes(): number;
/** Gets the minutes of a Date object using Universal Coordinated Time (UTC). */
getUTCMinutes(): number;
/** Gets the seconds of a Date object, using local time. */
getSeconds(): number;
/** Gets the seconds of a Date object using Universal Coordinated Time (UTC). */
getUTCSeconds(): number;
/** Gets the milliseconds of a Date, using local time. */
getMilliseconds(): number;
/** Gets the milliseconds of a Date object using Universal Coordinated Time (UTC). */
getUTCMilliseconds(): number;
/** Gets the difference in minutes between the time on the local computer and Universal Coordinated Time (UTC). */
getTimezoneOffset(): number;
/**
* Sets the date and time value in the Date object.
* #param time A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT.
*/
setTime(time: number): number;
/**
* Sets the milliseconds value in the Date object using local time.
* #param ms A numeric value equal to the millisecond value.
*/
setMilliseconds(ms: number): number;
/**
* Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC).
* #param ms A numeric value equal to the millisecond value.
*/
setUTCMilliseconds(ms: number): number;
/**
* Sets the seconds value in the Date object using local time.
* #param sec A numeric value equal to the seconds value.
* #param ms A numeric value equal to the milliseconds value.
*/
setSeconds(sec: number, ms?: number): number;
/**
* Sets the seconds value in the Date object using Universal Coordinated Time (UTC).
* #param sec A numeric value equal to the seconds value.
* #param ms A numeric value equal to the milliseconds value.
*/
setUTCSeconds(sec: number, ms?: number): number;
/**
* Sets the minutes value in the Date object using local time.
* #param min A numeric value equal to the minutes value.
* #param sec A numeric value equal to the seconds value.
* #param ms A numeric value equal to the milliseconds value.
*/
setMinutes(min: number, sec?: number, ms?: number): number;
/**
* Sets the minutes value in the Date object using Universal Coordinated Time (UTC).
* #param min A numeric value equal to the minutes value.
* #param sec A numeric value equal to the seconds value.
* #param ms A numeric value equal to the milliseconds value.
*/
setUTCMinutes(min: number, sec?: number, ms?: number): number;
/**
* Sets the hour value in the Date object using local time.
* #param hours A numeric value equal to the hours value.
* #param min A numeric value equal to the minutes value.
* #param sec A numeric value equal to the seconds value.
* #param ms A numeric value equal to the milliseconds value.
*/
setHours(hours: number, min?: number, sec?: number, ms?: number): number;
/**
* Sets the hours value in the Date object using Universal Coordinated Time (UTC).
* #param hours A numeric value equal to the hours value.
* #param min A numeric value equal to the minutes value.
* #param sec A numeric value equal to the seconds value.
* #param ms A numeric value equal to the milliseconds value.
*/
setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number;
/**
* Sets the numeric day-of-the-month value of the Date object using local time.
* #param date A numeric value equal to the day of the month.
*/
setDate(date: number): number;
/**
* Sets the numeric day of the month in the Date object using Universal Coordinated Time (UTC).
* #param date A numeric value equal to the day of the month.
*/
setUTCDate(date: number): number;
/**
* Sets the month value in the Date object using local time.
* #param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively.
* #param date A numeric value representing the day of the month. If this value is not supplied, the value from a call to the getDate method is used.
*/
setMonth(month: number, date?: number): number;
/**
* Sets the month value in the Date object using Universal Coordinated Time (UTC).
* #param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively.
* #param date A numeric value representing the day of the month. If it is not supplied, the value from a call to the getUTCDate method is used.
*/
setUTCMonth(month: number, date?: number): number;
/**
* Sets the year of the Date object using local time.
* #param year A numeric value for the year.
* #param month A zero-based numeric value for the month (0 for January, 11 for December). Must be specified if numDate is specified.
* #param date A numeric value equal for the day of the month.
*/
setFullYear(year: number, month?: number, date?: number): number;
/**
* Sets the year value in the Date object using Universal Coordinated Time (UTC).
* #param year A numeric value equal to the year.
* #param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. Must be supplied if numDate is supplied.
* #param date A numeric value equal to the day of the month.
*/
setUTCFullYear(year: number, month?: number, date?: number): number;
/** Returns a date converted to a string using Universal Coordinated Time (UTC). */
toUTCString(): string;
/** Returns a date as a string value in ISO format. */
toISOString(): string;
/** Used by the JSON.stringify method to enable the transformation of an object's data for JavaScript Object Notation (JSON) serialization. */
toJSON(key?: any): string;
}

Typescript recognizes the Date interface out of the box - just like you would with a number, string, or custom type. So Just use:
myDate : Date;

As others have mentioned the type is Date.
This type is usefull when you want to enforce at compile time that you really have a Date object. Below is a mistake that is often make (forgetting the new keyword) and we can see that it is caught at compile time.
const date: Date = new Date();
function logDayNumber(date: Date){
console.log(date.getDay())
}
// Works fine
logDayNumber(date);
// Compile time error which happens when you forget new a String we be produced from Date()
// Argument of type 'string' is not assignable to parameter of type 'Date'
logDayNumber(Date());

Related

Compare the Room Database and fetch the respective Data

We have Birthdate and Phone Number as user data. We need to Compare Today's date with Birthdate and fetch the Phone number to send an SMS.
We tried to use Repo class and View Model class, but unable to fetch details.
If you store the birthdate in a format supported by SQLite
see https://www.sqlite.org/lang_datefunc.html
Then you can use the 'now' timevalue (i.e. the date/ datetime NOW (i.e. when the query is run)).
As an example consider the following based upon a table (#Entity annotated class when dealing with Room) with 2 columns dob and altdob
two different formats
dob stores the time as a Long (more efficient storage wise)
altdob stores the date as a string format YYYY-MM-DD
4 rows are inserted with varying dates (both columns storing the same date)
Then a SELECT query that extracts the age (roughly) 3 ways and outputs the ages (3 columns output).
DROP TABLE IF EXISTS example; /* just in case table still exists */
CREATE TABLE IF NOT EXISTS example (dob INTEGER, altdob TEXT); /* create the table (room will do this) */
/* Add some data */
INSERT INTO example VALUES
(strftime('%s','1957-01-08'),'1957-01-08'),
(strftime('%s','1967-02-08'),'1967-02-08'),
(strftime('%s','1977-03-08'),'1977-03-08'),
(strftime('%s','1987-04-08'),'1987-04-08')
;
SELECT * FROM example; /* result 1 - the data as it is stored in the table */
/* result 2 the age in years (approx) using some of the datetime functions based upon the run/execution date */
SELECT
(strftime('%s','now')-dob) / (365 /* days in a year (close) */ * 24 /* hours in a day*/ * 60 /* mins in hour */ * 60 /* secs in minute*/) AS age,
(strftime('%s',date('now')) - strftime('%s',date(altdob))) / (365 * 24 * 60 * 60) AS altage,
date('now') - date(altdob)
FROM example;
DROP TABLE IF EXISTS example; /* cleanup demo environment */
When executed then the results are:-
Result 1
note the first column is the number of seconds since or before (if negative) 00:00:00 on 1st Jan 1970.
The second is obvious
the dates are the same just stored in different formats (both supported by the SQLite datetime functions)
Result 2
note that really there are not 365 days in a year (due to leap years)
Doing the above in Room (not mvvm for brevity/convenience)
First the Database related components:-
#Entity
data class Example(
#PrimaryKey
val dob: Long,
val altdob: String
)
data class POJOToGet3Ages(
val age: Int,
val altage: Int,
#ColumnInfo(name = "otheraltage") /* change to expect the output column name to be otheraltage instead of actual field name */
val notTheSameAsOutputColumnName: Int
)
#Dao
interface TheDAO {
#Insert(onConflict = OnConflictStrategy.IGNORE)
fun insert(example: Example): Long
#Query("SELECT " +
"(strftime('%s','now')-dob) / (365 /* days in a year (close) */ * 24 /* hours in a day*/ * 60 /* mins in hour */ * 60 /* secs in minute*/) AS age," +
"(strftime('%s',date('now')) - strftime('%s',date(altdob))) / (365 * 24 * 60 * 60) AS altage," +
"date('now') - date(altdob) AS otheraltage " +
"FROM example;")
fun getAllAges(): List<POJOToGet3Ages>
}
#Database(entities = [Example::class], exportSchema = false, version = 1)
abstract class TheDatabase: RoomDatabase() {
abstract fun getTheDAO(): TheDAO
companion object {
private var instance: TheDatabase?=null
fun getInstance(context: Context): TheDatabase {
if (instance==null) {
instance = Room.databaseBuilder(context,TheDatabase::class.java,"the_database.db")
.allowMainThreadQueries() /* run on main thread for brevity/convenience */
.build()
}
return instance as TheDatabase
}
}
}
To utilise the above some activity code (MainActivity) that will replicate the demo above (add the same 4 rows) and extract the ages based upon the date now and output the results to the log :-
class MainActivity : AppCompatActivity() {
lateinit var dbInstance: TheDatabase
lateinit var dao: TheDAO
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
dbInstance = TheDatabase.getInstance(this)
dao = dbInstance.getTheDAO()
dao.insert(Example(-409622400,"1957-01-08"))
dao.insert(Example(-91411200,"1967-02-08"))
dao.insert(Example(226627200,"1977-03-08"))
dao.insert(Example(544838400,"1987-04-08"))
for (ages in dao.getAllAges()) {
Log.d("DBINFO","Ages is ${ages.age} ALTAGE is ${ages.altage} OTHERALTAGE is ${ages.notTheSameAsOutputColumnName}")
}
}
}
When run the log includes:-
D/DBINFO: Ages is 66 ALTAGE is 66 OTHERALTAGE is 66
D/DBINFO: Ages is 55 ALTAGE is 55 OTHERALTAGE is 56
D/DBINFO: Ages is 45 ALTAGE is 45 OTHERALTAGE is 46
D/DBINFO: Ages is 35 ALTAGE is 35 OTHERALTAGE is 36

AppSync subtract/add day to current day in request mapping template

In my AppSync mapping request template, I need to add or subtract day from the current date.
All I could find are just formatting and parsing time helpers: Time Helpers in $util.time
#set( $todayString = $util.time.nowISO8601())
todayString is then like: 2019-08-23T09:00:00.000Z but I need to set new variables representing same time but one day prior current date or one day after it with the same formatting.
Is it possible at all using only vtl - mapping request template for my DynamoDB datasource?
I found a solution by using epoch time utils. Since it returns long, we can manipulate dates like in this sample and then convert it back to ISO8601 using existing time helper which accepts long value and returns formatted one further needed.
#set( $currentTimeEpoch = $util.time.nowEpochMilliSeconds())
#set( $fromStartEpoch = $currentTimeEpoch + (1000 * 60 * 60 * 24))
#set( $currentTime = $util.time.epochMilliSecondsToISO8601($currentTimeEpoch))
#set( $fromStart = $util.time.epochMilliSecondsToISO8601($fromStartEpoch))

Is it possible to find data from MySQL by month using JPA and java.time.LocalDate date format?

I creating an application, for that I need to find data by month using JPA and java.time.LocalDate. So, is it possible to retrieve data by month from mysql?
Thanks in advance for help.
First find start and end date of month and use between method of JPA to find data of current month.
LocalDate start = LocalDate.ofEpochDay(System.currentTimeMillis() / (24 * 60 * 60 * 1000) ).withDayOfMonth(1);
LocalDate end = LocalDate.ofEpochDay(System.currentTimeMillis() / (24 * 60 * 60 * 1000) ).plusMonths(1).withDayOfMonth(1).minusDays(1);
In Repository
List<Object> findByCreatedateGreaterThanAndCreatedateLessThan(LocalDate start,LocalDate end);
Its better to use the between keyword, it makes things allot shorter.
List<Object> findByCreatedateBetween(LocalDate start,LocalDate end);
Also if you want to use the LocalDate or LocalDateTime objects with Spring Data you should use the converter class Jsr310JpaConverters or else the documents will be stored as Blobs instead of Dates (which is bad for portability of the database). Please see this tutorial on how to implement the Converter.
https://www.mkyong.com/spring-boot/spring-boot-spring-data-jpa-java-8-date-and-time-jsr310/
tl;dr
YearMonth.now( ZoneId.of( "Pacific/Auckland" ) ) // Get current month for particular time zone.
.atDayOfMonth( 1 ) // Get the first date of that month.
.plusMonths( 1 ) // Get first of next month for Half-Open query.
Details
Assuming your column in MySQL is of DATE type…
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
Time zone
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
YearMonth
The YearMonth class represents an entire month. Getting the current month requires a time zone as discussed above. Around the beginning/ending of the month, the current moment could be “next” month in Auckland New Zealand while still “previous” month in Kolkata India.
YearMonth currentMonth = YearMonth.now( z ) ;
Get the first date of the month.
LocalDate start = currentMonth.atDayOfMonth( 1 ) ;
Half-Open
Generally best to use the Half-Open [) approach to defining a span of time, where the beginning is inclusive while the ending is exclusive. So defining a month means starting with the first date of the month and running up to, but not including, the first date of the following month.
LocalDate stop = start.plusMonths( 1 ) ;
Query
Do not use the BETWEEN command in SQL as it is fully closed [], both beginning and ending being inclusive. Half-Open uses >= & < logic.
SELECT when FROM tbl
WHERE when >= start
AND when < stop
;
it's also useful
#Query("from PogWorkTime p where p.codePto = :codePto and month(p.dateApply) = :month and year(p.dateApply) = :year")
Iterable<PtoExceptWorkTime> findByCodePtoAndDateApply_MonthAndDateApply_Year(#Param("codePto") String codePto,#Param("month") int month, #Param("year") int year);

Merge a Date object which has 04:00 as its time with another time string ("8:30am") into a new Date object

I have a mongo db with a document that has a date and a time separately.
Date object was intended to be just a date, so it has the time as
04:00 (time-zone adjusted to -4)
db.logs.findOne().date
ISODate("2014-08-05T04:00:00Z")
And there's a separate time field which is still a string
db.logs.findOne().time
8:30am
How do I merge them both into one field?
Do the combination client-side, using appropriate libraries to handle calendar and clock calculations, and then update/insert the document. MongoDB (as of 2.6, anyway) doesn't have facilities for updating to the combination server side.
db.logs.find().forEach(function(log) {
log.date = new Date(log.date.getFullYear(),
/* date */ log.date.getMonth(),
log.date.getDate(),
/* time */ parseInt(log.time)
/* + 12 if PM */ + (((log.time.charAt(log.time.length - 2) + log.time.charAt(log.time.length - 1)) === 'pm') ? 12 : 0));
db.logs.save(log);
})

Symfony dates are incorrect

I'm using Symfony and MongoDB.
I submit a form with: name="pupil[dateOfBirth]" -> 17-09-1985
And MongoDB stores it "a day earlier" as: 1985-09-16T22:00:00.000Z
How can i be sure mongo stores the right dates?
I used the BSON-type Date (9) in MongoDB
Doctrine will stored DateTimes in ISO 8601 format.
Given the time stored, this means your PHP timezone is 2 hours ahead of UTC, so 17th September 1985 becomes 16th September 1985 at 10pm. The Z at the end indicates the timezone, being UTC.
When you get the datetime value from Mongo, it should be converted back to 17th September 1985 at midnight.
There may be a way to store the DateTime values in Mongo as 1985-09-17T00:00:00.000+02:00
By explicitly setting the DateTime object to midnight and the right timezone in the Document setters, MongoDb stores it as "... 22:00:00.000Z" instead of "... 23:00:00.000Z".
/**
* Set dateOfBirth
*
* #param Date $dateOfBirth
* #return self
*/
public function setDateOfBirth($dateOfBirth)
{
$this->dateOfBirth = $dateOfBirth->modify('midnight')->setTimezone(new \DateTimeZone('Europe/Brussels'));
return $this;
}