Parse String Time to JS Date Obj - javascript

I am trying to convert a string of time such as "7:30am" to JavaScript Date Object like Sat Nov 18 2017 7:30:00 GMT-0500 (EST)
My approach:
function dateObj(d) { // date parser ...
var parts = d.split(/:|\s/),
date = new Date();
if (parts.pop().toLowerCase() == 'pm') parts[0] = (+parts[0]) + 12;
date.setHours(+parts.shift());
date.setMinutes(+parts.shift());
return date
}
var startTime = "7:30";
var endTime = "9:30pm";
var startDate = dateObj(startTime); // get date objects
var endDate = dateObj(endTime);
console.log(startDate, endDate)
I got Invalid Date for both startDate, endDate.
Try here:
function dateObj(d) { // date parser ...
var parts = d.split(/:|\s/),
date = new Date();
if (parts.pop().toLowerCase() == 'pm') {
parts[0] = parts[0] + 12;
}
date.setHours(parts.shift());
date.setMinutes(parts.shift());
return date
}
var startTime = "7:30am";
var endTime = "9:30pm";
var now = new Date();
var startDate = dateObj(startTime); // get date objects
var endDate = dateObj(endTime);
var test = dateObj(startTime)
console.log(startDate, endDate)

I would rather use a regular expression to extract the date elements and also add some error handling for the case the date format is not valid.
And do not forget also to handle 12am and 12pm. This needs extra handling in the code.
See below:
function dateObj(d) { // date parser ...
const rx = /(\d{1,2})\:(\d{1,2})\s*(am|pm)/g;
const parts = rx.exec(d);
if (parts === null) {
return "Not a valid date: " + d;
}
date = new Date();
const amPm = parts.pop().toLowerCase();
const hour = parseInt(parts[1]);
if (amPm === 'pm') {
if (hour !== 12) {
parts[1] = (parseInt(parts[1])) + 12;
}
} else if (amPm === 'am' && hour === 12) {
parts[1] = 0;
}
date.setHours(parts[1]);
date.setMinutes(parts[2]);
return date
}
var startTime = "7:30";
var endTime = "9:30pm";
var startDate = dateObj(startTime); // get date objects
var endDate = dateObj(endTime);
console.log(startDate, endDate)
console.log(dateObj("7:30 pm"))
console.log(dateObj("7:30 am"))
console.log(dateObj("7:30am"))
console.log(dateObj("12:30pm"))
console.log(dateObj("12:30 am"))

This is working for me if you enter 9:30 pm instead of 9:30pm, the white space needs to be there for regex:
function dateObj(d) {
var parts = d.split(/:|\s/),
date = new Date();
if (parts.pop().toLowerCase() == 'pm') {
parts[0] = parts[0] + 12;
}
date.setHours(parts[0]);
date.setMinutes(parts[1]);
return date;
}

It just needs a space before am/pm :
d = t => new Date(new Date().toDateString() + t.replace(/(.*\d)/, " $1 "))
console.log(d("7:30").toString())
console.log(d("7:30am").toString())
console.log(d("9:30pm").toString())

This will create a new Date object that includes the current time.
But it is based on the timezone of where the code is run.
var timeRe = /(\d+):(\d+)([amp]*)/gi;
function timeParse(time) {
var today = new Date();
var match = time.split(timeRe);
console.log(time, match);
if (match) {
var hours = parseInt(match[1],10)+(match[3].toLowerCase()==='pm'?12:0)%24;
today.setHours(hours);
today.setMinutes(parseInt(match[2],10));
today.setSeconds(0);
}
return today;
}
var startTime = "7:30";
var endTime = "9:30pm";
var startDate = timeParse(startTime); // get date objects
var endDate = timeParse(endTime);
console.log(startDate, endDate)

Related

remove timezone in my random date generator in javascript

This is my code. I make it random but the timezone is always in there and i dont know how to disappear the timezone, can someone help me with this I'am beginner in this thanks
var startDate = new Date("1990-01-01"); //YYYY-MM-DD
var endDate = new Date("2022-01-01"); //YYYY-MM-DD
function formatDate(date) {
const year = date.getFullYear();
/* getMonth returns dates from 0, so add one */
const month = date.getMonth() + 1;
const day = date.getDate();
return `${year}-${month < 10 ? '0' : ''}${ month }-${ day < 10 ? '0' : '' }${day}`
}
var getDateArray = function(start, end) {
return new Date(
start.getTime() + Math.random() * (end.getTime(0) - start.getTime(0))
);
}
var dateArr = getDateArray(startDate, endDate);
console.log(dateArr);
If you call the formatDate function you have in your code, I believe that will get rid of the timezone information.
var startDate = new Date("1990-01-01"); //YYYY-MM-DD
var endDate = new Date("2022-01-01"); //YYYY-MM-DD
function formatDate(date) {
const year = date.getFullYear();
/* getMonth returns dates from 0, so add one */
const month = date.getMonth() + 1;
const day = date.getDate();
return `${year}-${month < 10 ? '0' : ''}${ month }-${ day < 10 ? '0' : '' }${day}`
}
var getDateArray = function(start, end) {
return formatDate(new Date(
start.getTime() + Math.random() * (end.getTime(0) - start.getTime(0))
));
}
var dateArr = getDateArray(startDate, endDate);
console.log(dateArr);
All I did here was add a call to your formatDate function within the getDateArray function so that now the return of the getDateArray will no longer contain timezone information.
Create these 2 functions to change the date format.
function DateFormat(startDate)
{
const strYear = date("Y",strtotime(strDate));
const strMonth= date("n",strtotime(strDate));
const strDay= date("j",strtotime(strDate));
return "${strYear}$-${strMonth}-${strDay}";
}
function DateFormat(endDate)
{
const strYear = date("Y",strtotime(strDate));
const strMonth= date("n",strtotime(strDate));
const strDay= date("j",strtotime(strDate));
return "${strYear}$-${strMonth}-${strDay}";
}

Compare date passed to new Date() with the date returned by new Date();

I'm trying to check if a date is valid. If I pass 31/02/2018 to new Date it will return Tue Mar 03 1987 00:00:00 GMT+0000 (GMT) as 31/02/2018 is not a real date. So how can I compare the passed date with the return date of new Date? or am I going about this the wrong way altogether.
function isDateValid() {
var dob = "31/02/1994",
isValidDate = false;
var reqs = dob.split("/"),
day = reqs[0],
month = reqs[1],
year = reqs[2];
var birthday = new Date(year + "-" + month + "-" + day);
if (birthday === "????") {
isValidDate = true;
}
return isValidDate;
}
You can get the last day of each month by doing this;
var lastDay = new Date(month, year, 0).getDate();
In your case;
function isDateValid(date){
var isValidDate = false;
var reqs = date.split("/"),
day = reqs[0],
month = reqs[1],
year = reqs[2],
lastDay = new Date(month, year, 0).getDate();
if(day > 0 && day <= lastDay)
isValidDate = true;
return isValidDate;
}
This is what you are looking for. I left your code unchanged and stuck to your original request.
function isDateValid() {
var dob = "31/02/2018",
isValidDate = false;
var reqs = dob.split("/"),
day = reqs[0],
month = reqs[1],
year = reqs[2];
var birthday = new Date(year + "-" + month + "-" + day);
if (+year === birthday.getFullYear()&&
+day === birthday.getDate() &&
+month === birthday.getMonth() + 1) {
isValidDate = true;
}
return isValidDate;
}
console.log(isDateValid());

JavaScript/jQuery - Convert from 24 Hr Datetime String to 12Hr Date format?

var timeZone ="CDT"
var startDateTime = "2016-06-15 22:30:00.0";
this.outDate = function()
{
return getJustTime(startDateTime,timeZone);
}
function getJustTime(startDateTime,timeZone)
{
outDt = new Date(startDateTime.replace(/ /g,'T'));
return outDt;
}
**Expected Output**
this.outDate = "10.30 PM CDT";
I have two variables as above with 24 hour datetime string and i want to convert it into 12 hour format date string. What i am missing in the missing?
P.S : I can't use any datetime librarires.
Just write your own. The date object is very helpful.
function am_or_pm (date) {
var date_obj = new Date(date);
var hours = date_obj.getHours();
var morn_or_night;
// I wouldn't do this in production, but this is to make my logic really clear - I would probably use a conditional operator here.
// Handling Midnight
if (hours === 0) {
hours = 12;
morn_or_night = 'AM';
// Handling noon
} else if (hours === 12) {
morn_or_night = 'PM'
} else if (hours > 12) {
hours = hours - 12;
morn_or_night = 'PM';
} else {
morn_or_night = 'AM';
}
return hours.toString()+':'+date_obj.getMinutes()+' '+morn_or_night;
}
var timeZone ="CDT"
var startDateTime = "2016-06-15 22:30:00.0";
var slot='AM';
var a = startDateTime.split(" ");
var b = a[0].split("-");
var c = a[1].split(":");
if(c[0]>12){
slot='PM';
c[0] = c[0] - 12;
}
var date = c[0]+'.'+c[1]+' '+slot+' '+timeZone ;
console.log(date);

Convert local time to UTC in JavaScript

i have this code for working with dates.
<script language="javascript" type="text/javascript">
$("#Reports_SignUpDateAfter_container").datepicker({
changeYear: true,
changeMonth: true,
dateFormat: 'dd-mm-yy', //"dd-mm-yy",
gotoCurrent: true,
yearRange: '-10:+10',
onSelect: function() {
Reports_SignUpDateAfter_changeDate(false);
}
});
// react on manual text box editing
$("#Reports_SignUpDateAfter_container").change(function() {
Reports_SignUpDateAfter_changeDate(true);
});
function Reports_SignUpDateAfter_changeDate(manualChange) {
var newDate = $("#Reports_SignUpDateAfter_container").datepicker("getDate");
if (newDate != null) {
// add time information
newDate = DateUtils.copyTimeFrom("#Reports_SignUpDateAfter_local", newDate);
DateUtils.setDate("#Reports_SignUpDateAfter_local", newDate);
// convert local to UTC
Reports_SignUpDateAfter_localToUTC();
if (manualChange) {
$("#Reports_SignUpDateAfter_container").datepicker("setDate", newDate)
}
} else { // empty
$("#Reports_SignUpDateAfter_local").val("");
$("#Reports_SignUpDateAfter").val("");
}
}
// new date as UTC
function Reports_SignUpDateAfter_setDate(newDate) {
// store time into hidden inputs
DateUtils.setDate("#Reports_SignUpDateAfter", newDate);
// set local drop downs and hidden input
var dateString = DateUtils.getString(newDate);
dateString = DateUtils.fromUTCToLocal(dateString);
var localDate = DateUtils.getDateFromString(dateString);
DateUtils.setDate("#Reports_SignUpDateAfter_local", localDate);
$("#Reports_SignUpDateAfter_container").datepicker("setDate", localDate);
};
function Reports_SignUpDateAfter_localToUTC() {
// get string and convert to UTC
var dateString = $("#Reports_SignUpDateAfter_local").val();
dateString = DateUtils.fromLocalToUTC(dateString);
$("#Reports_SignUpDateAfter").val(dateString);
// conversion end
}
;
</script>
Problem is when i chose Start and End date like 2015-11-02 and end date 2015-11-04 it always convert me the date to UTC(-1:00h) but it doesn't consider the winter and summer date changes. For that date is should be the same(UTC and local). Is there any clue why is that so ?
var DateUtils = DateUtils || {
getDate: function (selector) {
var value = $(selector).val();
if (value == null || value == "") {
var date = new Date();
date.setHours(0);
date.setMinutes(0);
date = DateUtils.cleanSeconds(date);
return date;
}
return DateUtils.getDateFromString(value);
},
getClientTimeDifferenceFromUTC: function () {
var d = new Date()
return d.getTimezoneOffset();
},
setDate: function (selector, date) {
if (date != null) {
var old = DateUtils.getDate(selector);
old.setTime(date.getTime());
old = DateUtils.cleanSeconds(old);
$(selector).val(DateUtils.getString(old));
} else {
$(selector).val("");
}
},
// copies time from selector and date part from date
copyTimeFrom: function (selector, date) {
var value = $(selector).val();
if (date != null && value != null && value != "") {
var old = DateUtils.getDate(selector);
date.setHours(old.getHours());
date.setMinutes(old.getMinutes());
}
return date;
},
setHour: function (selector, hour) {
var old = DateUtils.getDate(selector);
old.setHours(hour);
old = DateUtils.cleanSeconds(old);
$(selector).val(DateUtils.getString(old));
},
setMinute: function (selector, minute) {
var old = DateUtils.getDate(selector);
old.setMinutes(minute);
old = DateUtils.cleanSeconds(old);
$(selector).val(DateUtils.getString(old));
},
cleanSeconds: function (date) {
date.setSeconds(0);
date.setMilliseconds(0);
return date;
},
// formats date into yyyy-mm-dd hh:mm format
getString: function (date) {
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
month = ('0' + month).slice(-2);
day = ('0' + day).slice(-2);
hours = ('0' + hours).slice(-2);
minutes = ('0' + minutes).slice(-2);
return year + "-" + month + "-" + day + " " + hours + ":" + minutes;
},
// formats string from yyyy-mm-dd hh:mm into date
getDateFromString: function (date) {
if (date == undefined || date == null) {
return null;
}
var m = date.match(/Date\((\d+)\)/); //handle .NET MVC Date format (i.e. "/Date(1426598616621)/")
if (m) {
return new Date(parseInt(m[1]));
}
var year = date.substring(0, 4);
var month = date.substring(5, 7);
var day = date.substring(8, 10);
var hours = date.substring(11, 13);
var minutes = date.substring(14, 16);
var newDate = new Date(year, month - 1, day, hours, minutes);
// newDate.setYear(year);
// newDate.setDate(1);
// newDate.setMonth(month - 1);
// newDate.setDate(day);
// newDate.setHours(hours);
// newDate.setMinutes(minutes);
newDate = DateUtils.cleanSeconds(newDate);
return newDate;
},
// dateString in format yyyy-mm-dd hh:mm
fromLocalToUTC: function (dateString) {
var date = this.fromLocalToUTCDate(dateString);
return this.getString(date);
},
fromLocalToUTCDate: function (dateString) {
var dateArray = dateString.substring(0, 10).split("-");
var timeArray = dateString.substring(11, 19).split(":");
if (timeArray[0] == null || timeArray[0] == "")
timeArray[0] = 0;
if (timeArray[1] == null || timeArray[1] == "")
timeArray[1] = 0;
var d = new Date(dateArray[0], dateArray[1] - 1, dateArray[2], timeArray[0], timeArray[1], 0);
// *****
// conversion from local date/time to UTC
var offSet = d.getTimezoneOffset() * 60000;
var millis = d.getTime() + offSet;
d.setTime(millis);
// *****
return d;
},
// dateString in format yyyy-mm-dd hh:mm
// returns date as string
fromUTCToLocal: function (dateString) {
var date = this.fromUTCToLocalDate(dateString);
return this.getString(date);
},
// dateString in format yyyy-mm-dd hh:mm
// returns date object
fromUTCToLocalDate: function (dateString, setOffset) {
var dateArray = dateString.substring(0, 10).split("-");
var timeArray = dateString.substring(11, 19).split(":");
if (timeArray[0] == null || timeArray[0] == "")
timeArray[0] = 0;
if (timeArray[1] == null || timeArray[1] == "")
timeArray[1] = 0;
var d = new Date(dateArray[0], dateArray[1] - 1, dateArray[2], timeArray[0], timeArray[1], 0);
// *****
// conversion from UTC to local date/time
if (setOffset != false) {
var offSet = d.getTimezoneOffset() * 60000;
var millis = d.getTime() - offSet;
d.setTime(millis);
}
// *****
return d;
},

Validate date for anyone over 18 with jQuery

I have a form on my site that should validate for anyone who is over 18.
var day = $("#dobDay").val();
var month = $("#dobMonth").val();
var year = $("#dobYear").val();
var age = 18;
var mydate = new Date();
mydate.setFullYear(year, month-1, day);
var currdate = new Date();
currdate.setFullYear(currdate.getFullYear() - age);
var output = currdate - mydate
if ((currdate - mydate) > 0){
// you are not 18
}
But it working totally opposite way. I would like the if statement to take action when user is over under 18 years old.
Thank you for your help in advance
check this DEMO
var day = 12;
var month = 12;
var year = 2006;
var age = 18;
var setDate = new Date(year + age, month - 1, day);
var currdate = new Date();
if (currdate >= setDate) {
// you are above 18
alert("above 18");
} else {
alert("below 18");
}
var day = $("#dobDay").val();
var month = $("#dobMonth").val();
var year = $("#dobYear").val();
var age = 18;
var mydate = new Date();
mydate.setFullYear(year, month-1, day);
var currdate = new Date();
currdate.setFullYear(currdate.getFullYear() - age);
if(currdate < mydate)
{
alert('You must be at least 18 years of age.');
}
Here is a somewhat lighter version that I tested:
var day = 1;
var month = 1;
var year = 1999;
var age = 18;
var cutOffDate = new Date(year + age, month, day);
if (cutOffDate > Date.now()) {
$('output').val("Get Outta Here!");
} else {
$('output').val("Works for me!");
}
The key is to add the minimum age to the birthdate and confirm that it is before the current date. You are checking if the current date minus the minimum age (basically the latest birthdate allowed) was greater than than the birthdate provided, which will give you the reverse.
18 year old validation rule for jQuery Validator plugin using addMethod function.
jQuery.validator.addMethod(
"validDOB",
function(value, element) {
var from = value.split(" "); // DD MM YYYY
// var from = value.split("/"); // DD/MM/YYYY
var day = from[0];
var month = from[1];
var year = from[2];
var age = 18;
var mydate = new Date();
mydate.setFullYear(year, month-1, day);
var currdate = new Date();
var setDate = new Date();
setDate.setFullYear(mydate.getFullYear() + age, month-1, day);
if ((currdate - setDate) > 0){
return true;
}else{
return false;
}
},
"Sorry, you must be 18 years of age to apply"
);
and
$('#myForm')
.validate({
rules : {
myDOB : {
validDOB : true
}
}
});
if it's working the opposite way have you tried swapping the > for a < on the second to last line?
I think it will be easier to understand if we rename the variables
mydate => givenDate
currdate => thresholdDate
if givenDate > thresholdDate => you are not 18
else => you are 18
i.e.
if ( givenDate > thresholdDate ){
// you are not 18
}
i.e
if ((givenDate - thresholdDate) > 0){
// you are not 18
}
i.e.
if ((mydate - currdate ) > 0){
// you are not 18
}

Categories