Epoch 0 to Date conversion using momnet.js - angularjs

I need to convert my epoch date to a Date object. I did this using the following code.
let abc = moment(maintenance.actualEndDate * 1000).format('DD/MMM/YYYY hh:mm');
but there is a high chance to 0 as the value for 'maintenance.actualEndDate'.
in this case the transalated date is showing the value as '01/01/1970 12:00'.
I actually need as an empty string in variable abc if the maintenance.actualEndDate is 0
I'm working on angular 4, is there any optimal solution to this?

If what you need is converting non-zero timestamps to a formatted date, and zero timestamps as empty string, a dedicated function would be nice:
function formatTimestamp(secondsSinceEpoch) {
return secondsSinceEpoch===0 ? '' : moment.unix(secondsSinceEpoch).format('DD/MMM/YYYY HH:mm');
}
//...
let abc = formatTimestamp(maintenance.actualEndDate);
(But this has nothing specific to angular)

Related

Date/Time Formatting in React

I am working with an API that returns Dates in the format 2022-03-01T11:32:37
Created: {this.props.proposal.OPENWHEN}
Created: 2022-03-01T11:32:37
How do i format this into DD/MM/YYY 24:00:00 ?
Thanks In Advance
Something like the following should be enough:
// Example expected argument: 2022-03-01T11:32:37
function prettifyDateTime (str) {
// Splitting the string between date and time
const [date, time] = str.split("T");
// Assuming 03 is the month and 01 is the day – otherwise, those could be swapped
const [year, month, day] = date.split("-")
// Added slashes and the space before the time
return `${day}/${month}/${year} ${time}`
}
prettifyDateTime("2022-03-01T11:32:37") // '01/03/2022 11:32:37'
Otherwise, I recommend using a date library like date-fns, dayJS, or moment.
You can use the Date object to accomplish what you want. It'll also accept other date formats. Here is one place to find Date description. You also get the benefit of rejecting invalid date formats
function prettifyDateTime(str) {
let date = new Date(str);
// There's other ways of formatting this return
return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
}

Display rows with current date as top result using react-table

I'm trying to create a table using react-table that would display data that matches today's date as the top result. For instance, today is 18 August 2021, so I would like any data entry that matches 08/18/2021 (mm/dd/yyyy format) to be displayed as the topmost entry in my table.
My current table looks like this
To give an example, I have already sorted my table in chronological order (from earliest to latest in mm/dd/yyyy format). However, I want any entry/entries in the table above with today's date (eg. Date of Operation: 08/18/2021) to be displayed at the top of the table. Thereafter, entries that do not match today's date will continue to be sorted in chronological order.
Can someone please let me know how this can be done? Thank you.
Without getting into the code details, you should be able to do this by supplying a custom sort function in the column definition API docs. We don't do this specific sort but we do have multiple custom sort functions, and I got the most help in writing them by reading the sortTypes.js file from the library source.
Here's a simple date sort function. You basically get two rows and a columnId and return -1, 0, or 1.
const prevDate = new Date(prev.original[columnId])
const prevIsDate = ...
const currDate = new Date(curr.original[columnId])
const currIsDate = ...
if (prevIsDate && currIsDate) {
return prevDate > currDate ? 1 : -1
} else {
if (!prevIsDate) {
return !currIsDate ? 0 : 1
} else {
return 1
}
}
}

How to check if a string date has passed a certain date

I have these strings:
yy = "19";
mm = "05";
dd = "31";
These represent the creation date of a certain object in my project. This object expires after one month. How do I check if the object has expired already?
(I came across this solution but thought there might be another way to do it.)
UPDATE: the string date apparently represent the actual expiry date
I ended up using the date format "yymmdd" so I can convert it to type long and do a simple number comparison.
sprintf(buffer, "%s%s%s", yy, mm, dd);
expiryDate = atol(buffer);
// get current date of format "yymmdd" as well
// getCurrentDate() is my function that gets the date from my SDK
currentDate = getCurrentDate();
if(expiryDate >= currentDate)
{
// expired object!
}

Date comparison validation in angular

I have 2 dates: 1.start and 2.end
format is like this.
12/4/2017 console.log(startDate);
12/20/2017 console.log(endDate);
I am writing a validation to check if the end date is bigger than start date throw error,but it is not working.
this is what i have tried:
var startDate = new Date(this.formB['startDateVal']).toLocaleDateString();
var endDate=new Date(this.formB['dueDateVal']).toLocaleDateString();
this is my condition:
if(endDate<startDate){
this.bucketMsgClass='fielderror';
this.bucketSuccessMsg = 'End Date is must lower than Start Date.';
}
where am i doing wrong.?
I've always just subtracted one of the dates from the other. If the result is negative, then Date 1 is before Date 2.
var d1 = new Date("12/12/2017");
var d2 = new Date("12/13/2017");
console.log(d1 - d2) // -86400000 (exactly 1 day in milliseconds)
So
if (d1 - d2 < 0) {
// d1 is smaller
}
Going through this link that explains comparing dates in javascript would probably help you understand the problem and solve it.
Compare two dates with JavaScript

NancyFX not serializing dates with a trailing Z to indicate UTC/Zulu

We store all of our dates in our database as UTC.
When they are returned to us from the API, they are in the following format
"createdDate":"2014-07-30T18:34:45"
But as you can see, the date doesn't have the trailing Z (which indicates to our Angular app that it's UTC / Zulu). It should look like this
"createdDate":"2014-07-30T18:34:45Z"
I do have the following setting in our Bootstrapper
JsonSettings.ISO8601DateFormat = true;
Where in my config can I ensure that there's a trailing Z for the purpose of UTC parsing?
What version of NancyFx are you using? Because in v0.23.0 or later, the JsonSerializer code has been changed to use the "o" date format instead of the "s" date format, which should give you the trailing Z that you're looking for. (But only on UTC datetimes.)
This is the commit that made this change. Note how DateTimeKind.Unspecified dates are treated as local; that might be one possible cause of your problem, if you're not explicitly creating your DateTime objects as DateTimeKind.Utc.
Below is the NancyFx code that serializes DateTime values, as it looks as of v0.23.0 (after that commit). From https://github.com/NancyFx/Nancy/blob/v0.23.0/src/Nancy/Json/JsonSerializer.cs, lines 480-518:
void WriteValue (StringBuilder output, DateTime value)
{
if (this.iso8601DateFormat)
{
if (value.Kind == DateTimeKind.Unspecified)
{
// To avoid confusion, treat "Unspecified" datetimes as Local -- just like the WCF datetime format does as well.
value = new DateTime(value.Ticks, DateTimeKind.Local);
}
StringBuilderExtensions.AppendCount(output, maxJsonLength, string.Concat("\"", value.ToString("o", CultureInfo.InvariantCulture), "\""));
}
else
{
DateTime time = value.ToUniversalTime();
string suffix = "";
if (value.Kind != DateTimeKind.Utc)
{
TimeSpan localTZOffset;
if (value >= time)
{
localTZOffset = value - time;
suffix = "+";
}
else
{
localTZOffset = time - value;
suffix = "-";
}
suffix += localTZOffset.ToString("hhmm");
}
if (time < MinimumJavaScriptDate)
time = MinimumJavaScriptDate;
long ticks = (time.Ticks - InitialJavaScriptDateTicks)/(long)10000;
StringBuilderExtensions.AppendCount(output, maxJsonLength, "\"\\/Date(" + ticks + suffix + ")\\/\"");
}
}
As you can see, requesting ISO 8601 date format will get you the 2014-07-30T18:34:45 format rather than the number of milliseconds since the epoch, but it will assume local times if the value being serialized has a Kind equal to DateTimeKind.Local.
So I have two suggestions for you: upgrade to v0.23 of NancyFx if you're still on v0.22 or earlier (v0.22 used the "s" date format, which does not include timezone info, for serializing DateTime values). And if the DateTime objects you're serializing aren't explicitly set to DateTimeKind.Utc, then make sure you specify Utc (since the default is Unspecified, which NancyFx treats as equivalent to Local).

Resources