Set null data as undefined in a function? - javascript

This is a function being used in a ReactJS code base.
Right now, dates that are passed into this function as "null" rather than a string are being rendered as Dec 31, 1969. But no date should be showing if the date is passed in as null.
I want to modify my function below to check for null dates and set those dates to undefined. How should I do that?
var formatTheDate = function(dateString, dateFormat) {
dateFormat = dateFormat || "MMMM DD YYYY, h:mm a";
return moment.utc(new Date(dateString)).local().format(dateFormat);
};

Just check the dateString before attempting to use it.
var formatTheDate = function(dateString, dateFormat) {
dateFormat = dateFormat || "MMMM DD YYYY, h:mm a";
return dateString
? moment.utc(new Date(dateString)).local().format(dateFormat)
: undefined;
};

Just return undefined or null or your choice if the date isn't valid or returns the default date from unix time 0.
var formatTheDate = function(dateString, dateFormat) {
var newDate = new Date(dateString);
//optionally return a value instead of undefined here
if(newDate == "Invalid Date" || newDate - new Date(null) == 0) return;
dateFormat = dateFormat || "MMMM DD YYYY, h:mm a";
return moment.utc(newDate).local().format(dateFormat);
};

Related

Convert UTC time to local time in Javascript, giving future date

I am getting created_at timestamp from backend in UTC format, which i need to render in browser. I am using date pipe in Angular-7. After reading few blogs and stackoverflow, i wrote this function below to get normal date format, which i can pass through date pipe in angular to format.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC
Issue: The output is in future date.
Input: "22-12-2020 03:44:09 UTC"
Output: "Fri Jan 22 2021 09:14:09 GMT+0530 (India Standard Time)"
getDateFromUTC(dateString: string) {
const date = dateString
.split(" ")[0]
.split("-")
.map((number) => parseInt(number));
const hours = dateString
.split(" ")[1]
.split(":")
.map((num) => parseInt(num));
const convertedDate = new Date(
Date.UTC(date[2], date[1], date[0], hours[0], hours[1],hours[2])
);
return convertedDate;
}
getDateFromUTC("22-12-2020 03:44:09 UTC")
What am i doing wrong?
Months in date object start from 0. So your code should decrease month by 1. Refer here.
Date.UTC(date[2], date[1] - 1, date[0], hours[0], hours[1],hours[2])
function getDateFromUTC(dateString) {
const date = dateString
.split(" ")[0]
.split("-")
.map((number) => parseInt(number));
const hours = dateString
.split(" ")[1]
.split(":")
.map((num) => parseInt(num));
const convertedDate = new Date(
Date.UTC(date[2], date[1] - 1, date[0], hours[0], hours[1], hours[2])
);
return convertedDate;
}
var localDate = getDateFromUTC('22-12-2020 03:44:09 UTC')
console.log(localDate.toString());
Althought, I am not sure why you have a date in string in first place.
Input date is not standard ISO 8601 date format YYYY-MM-DDTHH:mm:ss.sssZ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
So, you need to parse it first. Here is what I think you can get with the help of moment.js.
function getDateFromUTC(dateString) {
const parts = dateString.split(' ');
parts.pop();
dateString = parts.join(' ');
const d = moment.tz(
dateString,
'DD-MM-YYYY hh:mm:ss',
'UTC'
);
return d.toDate().toString();
}
console.log(getDateFromUTC('22-12-2020 03:44:09 UTC'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.31/moment-timezone-with-data.js"></script>
It returns Tue Dec 22 2020, 09:14:09 GMT+0530 (India Standard Time)
Browsers will automatically convert to Coordinated Universal Time (UTC) format automatically. You shouldn't need to do any date conversion.
Your back-end does not appear to be returning the correct UTC format according to ISO 8601 standard (UTC Dates end in 'Z').
The correct format for UTC is
[yyyy]-[MM]-[dd]T[HH]:[mm]:[ss].[sss]Z
For example:
2020-12-22T03:44:09.000Z
There is an issue a month is added I'm not sure why
function getDateFromUTC(dateString) {
//console.log(mydate);
var medate = dateString;
var day = dateString.substring(0, dateString.indexOf('-'));
dateString = dateString.replace('-', '=')
var month = dateString.substring(3, dateString.indexOf('-'))
console.log(month)
dateString = dateString.replace('-', '=')
var year = dateString.substring(6, dateString.indexOf(' '))
dateString = dateString.replace(' ', '=')
var hour = dateString.substring(11, dateString.indexOf(':'))
dateString = dateString.replace(':', '=')
var minute = dateString.substring(14, dateString.indexOf(':'))
dateString = dateString.replace(':', '=')
var second = dateString.substring(17, dateString.indexOf(' '))
medate = year+'-'+month+'-'+day+'T'+hour+':'+minute+':'+second;
//let utcDate = new Date(year+month+day+'T'+hour+':'+minute+':'+second);
let utcDate = new Date(medate)
var mydate = new Date(Date.UTC(
parseInt(year),
parseInt(month)-1,
parseInt(day),
parseInt(hour),
parseInt(minute),
parseInt(second),
0
));
//Apparently one month is added. I'm not sure why
console.log(mydate)
console.log(utcDate)
}
getDateFromUTC("22-12-2020 03:44:09 UTC");

javascript new Date and UTC date give same UTC time

I have the following JavaSCript code:
function getDate() {
return new Date().toJSON();
}
function getUtcDate() {
var date = new Date();
var now_utc = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
return new Date(now_utc).toJSON();
}
Bothe are returning the same date time, I was expecting getDate() to return my local time.. it doesn't as you can see in the image
I uploaded a jsfiddle here.
Any suggestions as to what's going on?
function getDate() {
return new Date().toLocaleString();
}
function getDateOffset() {
return new Date().getTimezoneOffset() / 60;
}
function getUtcDate() {
return new Date().toUTCString();
}
console.log('Local Date = '+ getDate());
console.log('local TimeZone Offset = '+ getDateOffset())
console.log('UTC Date = '+ getUtcDate());
Updated
var date = moment.utc().format();
console.log(date, "UTC");
var local = moment.utc(date).local().format();// add parameter to format to remove Timezone Offset
console.log(local, "UTC to Local + TimeZone Offset");
console.log('---------------------------------------------');
// you can use .format() from momentjs to return any format you want
var formattedDate = moment.utc().format('YYYY-MM-DD HH:mm:ss a');
console.log(formattedDate);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

Date format MMM dd yyyy, hh:mm a

I'm trying to present a Date inside ng-grid, I wrote a filter either the date is Expired or not, if so present a text otherwise a Date format MMM dd yyyy, hh:mm a
.filter("expiredDate", Filter);
function Filter($filter) {
return function (val) {
if (val === 'Expired')
return val;
var res = $filter('date')(val, 'MMM dd yyyy, hh:mm a');
return res;
}
}
This displays "/Date(1495366770000)/" instead of the Date and this is the value of val

Time conversion to ISO string is not correct with text field displayed

I have a text field in an MVC application that displays the date and time. The date is created using a datepicker and the time I add to the text field.
An example of the text is as follows:
10/23/2015 12:00 AM
I want to create a Date object with this time in ISO 8601 format. The date will be used to create an event in a fullcalendar jquery plugin.
When I try to create the Date object, the ISO string is:
2015-10-23T04:00:00.000Z
It should be 2015-10-23T00:00:00.000Z to represent midnight on that day.
This is my code:
<label id="schedule_start_date_lbl">Start Date: </label>
<input id="schedule_start_date" type="text" />
var startDayIndex = getDayIndex($('#rotation_start_time_txt').val());
$("#schedule_start_date").datepicker({
minDate: 0,
beforeShowDay: function (date) { return [date.getDay() == startDayIndex, ""] },
onSelect: function (dateText) {
$('#schedule_end_date').datepicker('option', 'minDate', dateText);
},
onClose: function (selectedDate) {
var rotation_txt = $('#rotation_start_time_txt').val();
var time = rotation_txt.substr(rotation_txt.indexOf(',') + 1);
$(this).val(selectedDate + time.toString(' HH:mm tt').toString());
}
});
$("#rotation_schedule_btn").click(function () {
//text value in schedule_start_date is: 10/23/2015 12:00 AM
var startDate = new Date($('#schedule_start_date').val()).toISOString();
//Value displayed is 2015-10-23T04:00:00.000Z
alert('startDate: ' + startDate);
});
Why is the time value off by 4 hours?
Thanks
UPDATE
I need to add to the Date objects after they are created. Creating the Date object using the function in the answer below is not creating it in UTC format. It can be displayed in that format but when I am creating events in the fullcalendar control, the date must be in UTC format and they are not.
This is my function to create a schedule:
$("#rotation_schedule_btn").click(function () {
//create member list order
var memberList = [];
$("#rotationList li").each(function () {
memberList.push({
id: $(this).attr('id'),
name: $(this).text(),
color: $(this).css('background-color')
})
});
//start and end date and time for new schedule
var startDate = convertTextToDate($('#schedule_start_date').val())
var endDate = convertTextToDate($('#schedule_end_date').val());
//remove events between startDate & endDate
$('#edit_calendar').fullCalendar('removeEvents', function (event) {
if (event.start.toDate() >= startDate && event.start.toDate() <= endDate
|| event.end.toDate() >= startDate && event.end.toDate() <= endDate) {
return true;
}
});
//Create events from rotation schedule selected
var newEvents = [];
var rotation_length = $('#rotation_type_select option:selected').val();
var rotation_start_date = new Date(startDate.toISOString());
var rotation_end_date = new Date(startDate.toISOString());
//End date is to midnight
endDate.setMinutes(endDate.getMinutes() + 1);
rotation_end_date.setDate(rotation_end_date.getDate() + parseInt(rotation_length));
var member_index = 0;
while (rotation_end_date <= endDate)
{
// alert('start date: ' + rotation_start_date.toISOString() + ' end date: ' + rotation_end_date.toISOString());
var event = new Object();
event = {
title: memberList[member_index].name,
start: new Date (rotation_start_date.toISOString()),
end: new Date (rotation_end_date.toISOString()),
objectID: memberList[member_index].id,
color: memberList[member_index].color,
allDay: true,
textColor: 'white'
};
newEvents.push(event);
eventsAdded.push(event);
rotation_start_date.setDate(rotation_start_date.getDate() + parseInt(rotation_length));
rotation_end_date.setDate(rotation_end_date.getDate() + parseInt(rotation_length));
if ((memberList.length - 1) == member_index) {
member_index = 0;
}
else {
member_index++;
}
}
//Render events on calendar
$('#edit_calendar').fullCalendar('addEventSource', newEvents);
}); //end create schedule button click
The function to convert the dates is the same as below but I renamed the function:
function convertTextToDate(dateValue)
{
var dateArray = dateValue.split(/\D/);
var pm = /pm$/i.test(dateValue);
var hour = (+dateArray[3] || 0) % 12 + (pm ? 12 : 0);
var date = new Date(Date.UTC(dateArray[2], dateArray[0] - 1, dateArray[1], hour, +dateArray[4] || 0, +dateArray[5] || 0));
return date;
}
What am i doing wrong?
Date.prototype.toISOString() is based on a 0 offset UTC timezone. So it is trying to normalize your current timezone back to 0 UTC, because when you do new Date() you create a new date based on your current time zone, that is why the method is trying to revert your date back to UTC time zone. You are probably right now in a time zone which is 4h behind UTC.
http://devdocs.io/javascript/global_objects/date/toisostring
In order to fix this, just append your string with " UTC" and it will no longer do the timezone shifting:
10/23/2015 12:00 AM UTC
It will generate:
"2015-10-23T00:00:00.000Z"
Do not use the Date constructor to parse strings, particularly non-standard strings. Ever. Manually parse the string.
Since you have a fixed format, it's pretty straight forward to create a date based on UTC with the format in the OP
// Parse date format mm/dd/yyyy hh:mm:ss AP as UTC
function parseMDYA(s) {
var b = s.split(/\D/);
var pm = /pm$/i.test(s);
var h = (+b[3]||0)%12 + (pm? 12 : 0);
return new Date(Date.UTC(b[2], b[0]-1, b[1], h, +b[4]||0, +b[5]||0));
}
var s = '10/23/2015 12:00 AM';
var d = parseMDYA(s);
document.write('Input string: ' + s +
'<br>UTC time: ' + d.toISOString() +
'<br>Local time: ' + d
);
Time parts that aren't supplied are treated as 0.

Parse DateTime string in JavaScript

Does anyone know how to parse date string in required format dd.mm.yyyy?
See:
Mozilla Core JavaScript Reference: Date object
Mozilla Core JavaScript Reference: String.Split
Code:
var strDate = "03.09.1979";
var dateParts = strDate.split(".");
var date = new Date(dateParts[2], (dateParts[1] - 1), dateParts[0]);
If you are using jQuery UI, you can format any date with:
<html>
<body>
Your date formated: <span id="date1"></span><br/>
</body>
</html>
var myDate = '30.11.2011';
var parsedDate = $.datepicker.parseDate('dd.mm.yy', myDate);
$('#date1').text($.datepicker.formatDate('M d, yy', parsedDate));
http://jsfiddle.net/mescalito2345/ND2Qg/14/
We use this code to check if the string is a valid date
var dt = new Date(txtDate.value)
if (isNaN(dt))
refs:
http://momentjs.com/docs/#/parsing/string/
If you use moment.js, you can use "string" + "format" mode
moment(String, String);
moment(String, String, String);
moment(String, String, Boolean);
moment(String, String, String, Boolean);
ex:
moment("12-25-1995", "MM-DD-YYYY");
I'v been used following code in IE. (IE8 compatible)
var dString = "2013.2.4";
var myDate = new Date( dString.replace(/(\d+)\.(\d+)\.(\d+)/,"$2/$3/$1") );
alert( "my date:"+ myDate );
ASP.NET developers have the choice of this handy built-in (MS JS must be included in page):
var date = Date.parseLocale('20-Mar-2012', 'dd-MMM-yyyy');
http://msdn.microsoft.com/en-us/library/bb397521%28v=vs.100%29.aspx
Use Date object:
var time = Date.parse('02.02.1999');
document.writeln(time);
Give: 917902800000
This function handles also the invalid 29.2.2001 date.
function parseDate(str) {
var dateParts = str.split(".");
if (dateParts.length != 3)
return null;
var year = dateParts[2];
var month = dateParts[1];
var day = dateParts[0];
if (isNaN(day) || isNaN(month) || isNaN(year))
return null;
var result = new Date(year, (month - 1), day);
if (result == null)
return null;
if (result.getDate() != day)
return null;
if (result.getMonth() != (month - 1))
return null;
if (result.getFullYear() != year)
return null;
return result;
}
you can format date just making this type of the code.In javascript.
// for eg.
var inputdate=document.getElementById("getdate").value);
var datecomp= inputdate.split('.');
Var Date= new Date(datecomp[2], datecomp[1]-1, datecomp[0]);
//new date( Year,Month,Date)

Categories