I want to make a js date object based on strings in format YYYYMMDD and HHMMSS.
function makeTimeStamp(myDate, MyTime){
// myDate format YYYYMMDD
// myTime format HHMMSS
var YYYY = myDate.substring(0, 3);
var MM = myDate.substring(4, 5);
var DD = myDate.substring(6,7);
var HH = myTime.substring(0,1);
var MM = myTime.substring(2,3);
var SS = myTime.substring(4,5);
jsDate =
}
If you meant to be creating a Date object for given year, month, day, hours, minutes and seconds, you can use new Date(year, month - 1, day, hours, minutes, seconds) to create a Date instance for it. Note that the month is 0 based, January is 0, February 1, etc. Hence the MM - 1;
function stringToDate(myDate, myTime){
// myDate format YYYYMMDD
// myTime format HHMMSS
var YYYY = myDate.substr(0, 4);
var MM = myDate.substr(4, 2);
var DD = myDate.substr(6, 2);
var HH = myTime.substr(0, 2);
var mm = myTime.substr(2, 2);
var SS = myTime.substr(4, 2);
var jsDate = new Date(YYYY, MM - 1, DD, HH, mm, SS);
return jsDate;
}
// returns a Date object for given date and time
var jsDate = stringToDate("20110818", "191500");
// returns 1313687700000
var timestamp = jsDate.getTime();
Note that I'm using string.substr(start_position, length) as you can easily see the length of the returned value.
You can try Date.js which is a date library. http://www.datejs.com/
You can convert those date and time formats in to ISO format pretty easily (e.g. "2011-08-18T12:34:56") and use a regular expression to make sure the arguments are formatted properly:
function makeTimestamp(myDate, myTime) {
var ds = myDate.match(/^(\d{4})(\d\d)(\d\d)$/)
, ts = myTime.match(/^(\d\d)(\d\d)(\d\d)$/);
if (!ds || !ts) { return null; }
return new Date(ds.slice(1,4).join("-") + "T" + ts.slice(1,4).join(":"));
}
var d = makeTimestamp('20110818', '123456');
d // => Fri Aug 19 2011 12:34:56 GMT-0400 (EDT)
you can try this: https://www.npmjs.com/package/timesolver
npm i timesolver
use it in your code:
const timeSolver = require('timeSolver');
const date = new Date();
const dateString = timeSolver.getString(date, 'YYYYMMDD HHMMSS');
`
You can get date string by using this method:
const dateString = timeSolver.getString(date, format);
Hope this will help you!
Related
how can i extract time from datetime format.
my datetime format is given below.
var datetime =2000-01-01 01:00:00 UTC;
I only want to get the time 01.00 as 01
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString
Date.prototype.toLocaleTimeString()
Returns a string with a locality sensitive representation of the time portion of this date based on system settings.
var time = datetime.toLocaleTimeString();
Update:
The new locales and options arguments let applications specify the
language whose formatting conventions should be used and customize the
behavior of the function. In older implementations, which ignore the
locales and options arguments, the locale used and the form of the
string returned are entirely implementation dependent.
// Depending on timezone, your results will vary
var event = new Date('August 19, 1975 23:15:30 GMT+00:00');
console.log(event.toLocaleTimeString('en-US'));
// expected output: 1:15:30 AM
console.log(event.toLocaleTimeString('it-IT'));
// expected output: 01:15:30
What about these methods
new Date().getHours()
new Date().getMinutes()
For example:
var d = new Date();
var n = d.getHours();
Edited
Return the hour, according to universal time:
new Date().getUTCHours()
Example:
var d = new Date();
var n = d.getUTCHours();
As an alternative if you want to get the time from a string -
var datetime ="2000-01-01 01:00:00 UTC";
var myTime = datetime.substr(11, 2);
alert(myTime) //01
with the moment.js library it works in this way:
var result = moment().format('hh');
alert(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
var datetime = ("2000-01-01 01:00:00 UTC");
var d1 = new Date(datetime);
var minute = d1.getUTCMinutes();
var hour = d1.getUTCHours();
if(minute > 0)
alert(hour+"."+minute);
else
alert(hour);
Demo
var date1 = new Date(1945,10,20, 17,30)
var date2 = new Date(1970,1,8, 12,00)
console.log(date1.getHours() - 8 + (date1.getMinutes()/60))
console.log(date2.getHours() - 8 + (date2.getMinutes()/60))
Use the following code:
var datetime = "2000-01-01 01:00:00 UTC";
var dt = new Date(datetime);
var hr = dt.getUTCHours();
if(hr > 12) {
hr -= 12;
}
alert(hr);
refer this link also.
I have done it! It looks like this:
console.log(new Date().toLocaleTimeString() + " " + new Date().getSeconds() + " seconds");
Assuming you have a Date object like
var datetime = new Date("2000-01-01 01:00:00 UTC"); // might not parse correctly in every engine
// or
var datetime = new Date(Date.UTC(2000, 0, 1, 1, 0, 0));
then use the getUTCHours method:
datetime.getUTCHours(); // 1
I hope you can find a solution here.
let preDateTime = new Date("2022-03-31 22:26:00");
let newTime = preDateTime.toLocaleTimeString('en-US');
let hour = newTime.split(":")[0];
let amPm = newTime.split(" ")[1];
let seconds = newTime.split(":")[2].replace(amPm,'');;
let noAmPm = newTime.replace(amPm,'');
let noAmPmSeconds = noAmPm.replace(":"+seconds,'');
let noSeconds = newTime.replace(":"+seconds,' ');
if(parseInt(hour)<9){
newTime = "0"+newTime;
noAmPm = "0"+noAmPm
noSeconds= "0"+noSeconds
noAmPmSeconds = "0"+noAmPmSeconds;
}
console.log(newTime); //10:26:00 PM
console.log(noAmPm); //10:26:00
console.log(noSeconds); //10:26 PM
console.log(noAmPmSeconds); //10:26
i have this time format :
DateTime(2015, 5, 11, 12, 0, 0)
i would like to know if i can convert it into a time stamp.
i have made this convert function from ISO 8601 to Timestamp and i would like to know if i can adapt it to this time format :
var myDate = new Date("2017-07-31T15:30:00+0000");
var offset = myDate.getTimezoneOffset() * 60 * 1000;
var withOffset = myDate.getTime();
var withoutOffset = withOffset - offset;
console.log(myDate.getTimezoneOffset()*60 * 1000)
console.log('with Offset ' + withOffset);
console.log('without Offset (timeStamp of your timezone) ' +withoutOffset);
did you try
Date.parse(your date here)/1000
Date.parse(new Date(2015, 5, 11, 12, 0, 0))/1000
you can use the library momentjs to convert it.
Here you are assigning an instance of momentjs to CurrentDate:
var CurrentDate = moment();
Here just a string, the result from default formatting of a momentjs instance:
var CurrentDate = moment().format();
And here the number of seconds since january of... well, unix timestamp:
var CurrentDate = moment().unix();
momentjs guide
Parsing dates is a pain in JavaScript as there's no extensive native support. However you could do something like the following by relying on the Date(year, month, day [, hour, minute, second, millisecond]) constructor signature of the Date object.
var dateString = '17-09-2013 10:08',
dateTimeParts = dateString.split(' '),
timeParts = dateTimeParts[1].split(':'),
dateParts = dateTimeParts[0].split('-'),
date;
date = new Date(dateParts[2], parseInt(dateParts[1], 10) - 1, dateParts[0], timeParts[0], timeParts[1]);
console.log(date.getTime()); //1379426880000
console.log(date); //Tue Sep 17 2013 10:08:00 GMT-0400
I've got a string from an input field which I use for date with a format like this 25-02-2013. Now I want to compare the string with today's date. I want to know if the string is older or newer then today's date.
Any suggestions?
<script type="text/javascript">
var q = new Date();
var m = q.getMonth()+1;
var d = q.getDay();
var y = q.getFullYear();
var date = new Date(y,m,d);
mydate=new Date('2011-04-11');
console.log(date);
console.log(mydate)
if(date>mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
</script>
Exact date comparsion and resolved bug from accepted answer
var q = new Date();
var m = q.getMonth();
var d = q.getDay();
var y = q.getFullYear();
var date = new Date(y,m,d);
mydate=new Date('2011-04-11');
console.log(date);
console.log(mydate)
if(date>mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
You can use a simple comparison operator to see if a date is greater than another:
var today = new Date();
var jun3 = new Date("2016-06-03 0:00:00");
if(today > jun3){
// True if today is on or after June 3rd 2016
}else{
// Today is before June 3rd
}
The reason why I added 0:00:00 to the second variable is because without it, it'll compare to UTC (Greenwich) time, which may give you undesired results. If you set the time to 0, then it'll compare to the user's local midnight.
Using Javascript Date object will be easier for you. But as the Date object does not supports your format i think you have to parse your input string(eg: 25-02-2013) with '-' to get date month and year and then use Date object for comparison.
var x ='23-5-2010';
var a = x.split('-');
var date = new Date (a[2], a[1] - 1,a[0]);//using a[1]-1 since Date object has month from 0-11
var Today = new Date();
if (date > Today)
alert("great");
else
alert("less");
If your date input is in the format "25-02-2013", you can split the string into DD, MM and YYYY using the split() method:
var date_string="25-02-2013";
var day = parseInt(date_string.split("-")[0]);
var month= parseInt(date_string.split("-")[1]);
var year = parseInt(date_string.split("-")[2]);
The parseInt() function is used to make the string into an integer. The 3 variables can then be compared against properties of the Date() object.
The most significant points which needs to be remembered while doing date comparison
Both the dates should be in same format to get accurate result.
If you are using date time format and only wants to do date comparison then make sure you convert it in related format.
Here is the code which I used.
var dateNotifStr = oRecord.getData("dateNotif");
var today = new Date();
var todayDateFormatted = new Date(today.getFullYear(),today.getMonth(),today.getDate());
var dateNotif=new Date(dateNotifStr);
var dateNotifFormatted = new Date(dateNotif.getFullYear(),dateNotif.getMonth(),dateNotif.getDate());
Well, this can be optimized further but this should give you clear idea on what is required to make dates in uniform format.
Here's my solution, getDay() doesn't work like some people said because it grabs the day of the week and not the day of the month. So instead you should use getDate like I used below
var date = new Date();
var m = date.getMonth();
var d = date.getDate();
var y = date.getFullYear();
var todaysDate = formateDate(new Date(y,m,d));
console.log("Todays date is: " + todaysDate)
const formateDate = (assignmentDate) => {
const date = new Date(assignmentDate)
const formattedDate = date.toLocaleDateString("en-GB", {
day: "numeric",
month: "long",
year: "numeric"
})
return formattedDate
}
The function below is just to format the date into a legible format I could display to my users
<script type="text/javascript">
// If you set the timezone then your condition will work properly,
// otherwise there is a possibility of error,
// because timezone is a important part of date function
var todayDate = new Date().toLocaleString([], { timeZone: "Asia/Dhaka" }); //Today Date
var targetDate = new Date('2022-11-24').toLocaleString([], { timeZone: "Asia/Dhaka" });
console.log('todayDate ==', todayDate); // todayDate == 10/31/2022, 12:15:08 PM
console.log('targetDate ==', targetDate); // targetDate == 11/24/2022, 6:00:00 AM
if(targetDate >= todayDate)
{
console.log("Today's date is small");
}
else
{
console.log("Today's date is big")
}
</script>
I have a string that contains 8 digits that represent a date. For example:
20120515
I'd like to compare it with today's date, created in this manner:
var currentDate = new Date();
How can I convert the "8 digit date string" to a suitable date format in order to compare it to currentDate?
Use the substring method and substring off 4 elements and assign it to your new date for the year. Then substring off two elements at a time and store the month and date accordingly.
var dateString = "20120515";
var year = dateString.substring(0,4);
var month = dateString.substring(4,6);
var day = dateString.substring(6,8);
var date = new Date(year, month-1, day);
var currentDate = new Date();
Now you can compare the two dates with the normal operators.
If you want a small date library you can use moment.js.
var a = moment("20120515", "YYYYMMDD");
// then use any of moment's manipulation or display functionality
a.format("MMM Do YYYY"); // May 15th 2012
a.fromNow(); // 14 hours ago
a.calendar(); // Today at 12:00 AM
To correctly handle the local time zone, it must explicitly summed to the calculated time
function dateStringToDate(dateString) {
try {
var year = dateString.substring(0, 4);
var month = dateString.substring(4, 6);
var day = dateString.substring(6, 8);
var date = new Date(year, month - 1, day);
const offset = date.getTimezoneOffset()
date = new Date(date.getTime() - (offset * 60 * 1000));
return date;
} catch (error) {
return null;
}
}
function dateStringToDate(dateString) {
try {
var year = dateString.substring(0, 4);
var month = dateString.substring(4, 6);
var day = dateString.substring(6, 8);
var date = new Date(year, month - 1, day);
const offset = date.getTimezoneOffset()
date = new Date(date.getTime() - (offset * 60 * 1000));
return date;
} catch (error) {
return null;
}
}
console.log(dateStringToDate("20211212"))
console.log(dateStringToDate("20211213"))
console.log(dateStringToDate("20211214"))
...some other "one-liner" ways to accomplish this:
(They take a value like dts='20020704'; and return date object [dt].)
var dt=new Date(dts.slice(0,4), (dts[4]+dts[5])-1, dts[6]+dts[7]);
...or...
var m=dts.match(/(....)(..)(..)/), dt=new Date(m[1],m[2]-1,m[3]);
...or...
var m=dts.match(/.{1,2}/g), dt=new Date(m[0]+m[1],m[2]-1,m[3]);
The last one's shortest, but the first is probably most efficient, since it doesn't use regex (but that's irrelevant, unless you're processing LOTS of data using this). I like the middle one best since it's easy to see what's happening.
I have a unix timestamp, e.g., 1313564400000.00. How do I convert it into Date object and get month/year/day accordingly? The following won't work:
function getdhm(timestamp) {
var date = Date.parse(timestamp);
var month = date.getMonth();
var day = date.getDay();
var year = date.getYear();
var formattedTime = month + '/' + day + '/' + year;
return formattedTime;
}
var date = new Date(1313564400000);
var month = date.getMonth();
etc.
This will be in the user's browser's local time.
An old question, but none of the answers seemed complete, and an update for 2020:
For example: (you may have a decimal if using microsecond precision, e.g. performance.now())
let timestamp = 1586438912345.67;
And we have:
var date = new Date(timestamp); // Thu Apr 09 2020 14:28:32 GMT+0100 (British Summer Time)
let year = date.getFullYear(); // 2020
let month = date.getMonth() + 1; // 4 (note zero index: Jan = 0, Dec = 11)
let day = date.getDate(); // 9
And if you'd like the month and day to always be a two-digit string (e.g. "01"):
let month = (date.getMonth() + 1).toString().padStart(2, '0'); // "04"
let day = date.getDate().toString().padStart(2, '0'); // "09"
For extended completeness:
let hour = date.getHours(); // 14
let minute = date.getMinutes(); // 28
let second = date.getSeconds(); // 32
let millisecond = date.getMilliseconds(); // 345
let epoch = date.getTime(); // 1586438912345 (Milliseconds since Epoch time)
Further, if your timestamp is actually a string to start (maybe from a JSON object, for example):
var date = new Date(parseFloat(timestamp));
or for right now:
var date = new Date(Date.now());
More info if you want it here (2017).
Instead of using parse, which is used to convert a date string to a Date, just pass it into the Date constructor:
var date = new Date(timestamp);
Make sure your timestamp is a Number, of course.