How to parse a string into a date object at JavaScript? - javascript

How to parse a string into a date object at JavaScript (without using any 3d party) that is at dd-MM-yyyy HH:mm (all of them numbers) format?

var p = "04-22-1980 12:22".split(/-|\s+|:/);
// new Date(year, month, day [, hour, minute, second, millisecond ])
new Date(p[2], p[0] - 1, p[1], p[3], p[4]);
// => Tue Apr 22 1980 12:22:00 GMT-0500 (Central Daylight Time)

DateJS is your friend: http://www.datejs.com/
It parses pretty much anything reasonable you throw at it:
// Convert text into Date
Date.parse('today');
Date.parse('t + 5 d'); // today + 5 days
Date.parse('next thursday');
Date.parse('February 20th 1973');
Date.parse('Thu, 1 July 2004 22:30:00');
It's not perfect, but it does a pretty good job.

Related

how to convert date to 20160422060933.0Z format?

In angular I have to save data to database in this time format 20160422060933.0Z ?
Someone told me that this is Microsoft time format. I don't know how to convert date to this format, anyone encountered this before?
2016 is a year, 04 is a month, and 22 is a date but i don't know what 060933.0Z is. We use Dreamfactory API and SQL Server
Later edit: based on another answer, actually this seems to be a standard format colloquially called a "LDAP date". See Converting a ldap date for some details on the format (and how to parse it in Java). It can for sure be easily parsed with any typical JS date library or even without any library.
Let's break it down into pieces.
2016 = full year
04 = month, padded to 2 digits
22 = day of month, likely also padded to 2 digits
06 = hour of day, padded to 2 digits, likely on a 24h scale
09 = minute of the hour, padded to 2 digits
33 = second of the minute, likely padded to 2 digits
. = literal
0 = probably "second fraction"
Z = offset from UTC. Z meaning UTC.
Parsing it
You have several options to parse it:
If you assume you're going to always get an UTC datetime from the backend, you can naively parse it in JavaScript just by extracting the relevant substrings.
const input = '20160422060933.0Z';
new Date(Date.UTC(
input.substr(0, 4), // year
input.substr(4, 2) - 1, // month is 0-indexed
input.substr(6, 2), // day
input.substr(8, 2), // hour
input.substr(10, 2), // minute
input.substr(12, 2), // second
("0." + input.split(/[.Z]/gi)[1]) * 1000 // ms
));
// Fri Apr 22 2016 09:09:33 GMT+0300 (Eastern European Summer Time)
You can be a little creative and actually manipulate the string into an ISO format. Then you can just use the native Date.parse function, which supports parsing ISO strings (other formats are browser-dependent). The advantage is that it'll support dates that are not UTC as well.
new Date(Date.parse(
input.substr(0, 4) + "-" + // year, followed by minus
input.substr(4, 2) + "-" + // month, followed by minus
input.substr(6, 2) + "T" + // day, followed by minus
input.substr(8, 2) + ":" + // hour, followed by color
input.substr(10, 2) + ":" + // minute, followed by color
input.substr(12, 2) + // second
input.substr(14) // the rest of the string, which would include the fraction and offset.
))
// Fri Apr 22 2016 09:09:33 GMT+0300 (Eastern European Summer Time)
Use a library like luxon, momentjs, etc. This you might already have a JS library in your project. You'd need to build a date format pattern to parse this format into a native Date object or some other library-specific object. For example, with momentjs you'd do:
moment("20160422060933.0Z", "YYYYMMDDHHmmss.SZ")
// Fri Apr 22 2016 09:09:33 GMT+0300 (Eastern European Summer Time)
Formatting into it
This side of the operation is even simpler.
Without any date library, you just need to get rid of the "-", ":" and "T" separators from the ISO format. So you can just do the following:
new Date().toISOString().replace(/[:T-]/g, "")
// '20230209175305.421Z'
If you want to use a date library, then you just do the reverse, format operation using the same pattern as for parsing. Eg. in momentjs:
moment(new Date()).utc().format("YYYYMMDDHHmmss.S[Z]")
// "20230209175222.5Z"
(note that I needed to place the "Z" in brackets due to https://github.com/moment/moment-timezone/issues/213).
Just a side note to the other answer here:
You can use ldap2date npm package for parsing, should be not that "heavy" as moment.
Code:
import ldap2date from "ldap2date";
// or import { parse, toGeneralizedTime } from "ldap2date";
const dateString = "20160422060933.0Z";
const date = ldap2date.parse(dateString);
console.log(date.toUTCString());
// Fri, 22 Apr 2016 06:09:33 GMT
const str = ldap2date.toGeneralizedTime(date);
console.log(str);
// 20160422060933Z (note: no period.)
console.log(str.replace("Z", ".0Z"));
// 20160422060933.0Z
function getLdapString(date) {
return ldap2date.toGeneralizedTime(date);
}
const d = new Date();
console.log(getLdapString(d), d.toISOString());
// 20230209181603.965Z 2023-02-09T18:16:03.965Z
And some monkey-patching to match "format":
function getLdapString(date) {
return date.getMilliseconds() !== 0
? ldap2date.toGeneralizedTime(date)
: ldap2date.toGeneralizedTime(date).replace("Z", ".0Z");
}
const d = new Date();
d.setMilliseconds(15);
const d1 = new Date();
d1.setMilliseconds(0);
console.log("Date with milliseconds: ", d.toUTCString(), getLdapString(d));
console.log("Date without milliseconds: ", d1.toUTCString(), getLdapString(d1));
// Date with milliseconds: Thu, 09 Feb 2023 18:22:27 GMT 20230209182227.15Z
// Date without milliseconds: Thu, 09 Feb 2023 18:22:27 GMT 20230209182227.0Z
Or to ignore milliseconds part completelly
function getLdapString(date) {
const copy = new Date(date);
copy.setMilliseconds(0);
return ldap2date.toGeneralizedTime(copy).replace("Z", ".0Z");
}
console.log("Date with milliseconds: ", d.toUTCString(), getLdapString(d));
console.log("Date without milliseconds: ", d1.toUTCString(), getLdapString(d1));
// Date with milliseconds: Thu, 09 Feb 2023 18:29:50 GMT 20230209182950.0Z
// Date without milliseconds: Thu, 09 Feb 2023 18:29:50 GMT 20230209182950.0Z

Javascript show next possible delivery date

I have a website, where the client can see the delivery date.
Here is the code
function getProductRecordHTML(Product, index, quantity, ProductType, blok)
{
var manufacturer = "", article_show = "", name = "";
var time_to_exe = Product.time_to_exe;
var displayDate;
if(time_to_exe == 6)
{
const date = new Date();
date.setDate(date.getDate() + parseInt(time_to_exe));
displayDate = date.toLocaleDateString();
}
if (displayDate) {
time_to_exe = displayDate;
} else {
time_to_exe = time_to_exe + "d";
}
For now, time_to_exe gives the delivery time in days
This code calculates the next delivery date just by adding these 6 days to the current date.
My main goal is to get the period from Monday to Wednesday at 12 pm, if it's true then time_to_exe shows the date of next Monday (for example 23/08/2021), but if it's false (for example it's period from Wednesday after 12 pm till Sunday 11:59 pm) then time_to_exe show Monday date 1-week after (for example 30/08/2021).
I hope explained clearly.
Already many thanks to the user #Christopher for helping before.
One way to work with dates much easier is to use a library like moment.js (which I have been using for years), or maybe even better a newer library like Luxon, since moment.js is going into maintenance mode.
Let's see how you would achieve your date calculation using moment.js:
var orderDateTime = moment('08/18/2021 8:15 am');
// Get Sunday (first day) of this week and add 3 days (to get to Wednesday) and set the time to 11:59am
var cutOffDate = moment().startOf('week').add(3,'days').set({'hour': 11, 'minute': 59, 'second': 59});
// Initialize delivery date from order date
var deliveryDate = orderDateTime.clone();
if (orderDateTime.isSameOrBefore(cutOffDate)) {
deliveryDate = deliveryDate.add(1,'week').startOf('week').add(1,'day'); // Monday next week
} else {
deliveryDate = deliveryDate.add(2,'week').startOf('week').add(1,'day'); // Monday the week after next
}
alert("Delivery Date is "+deliveryDate.format("MM/DD/YYYY"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
That's all you need for your calculation.
You can also find a fiddle of the code above at https://jsfiddle.net/yLpf3vxj/
The Javascript Date object includes a getDay() method that returns a numerical value for the day of the week. From this it's possible to work out the previous Monday's date, and then add 7 or 14 depending on the original date.
This function takes a JavaScript Date object and returns the relevant Monday as another Date.
Note that setDate() will update month and year as appropriate if the date being set is outside the current month.
function getMonday(orderDate) {
orderDate = orderDate || new Date();
if (!(orderDate instanceof Date)) {
throw "Invalid date";
}
// Get the date last Monday
let lastMonday = new Date(orderDate);
lastMonday.setDate(lastMonday.getDate()-lastMonday.getDay()+1);
// If order date is before Wednesday noon, deliver next Monday. Add 7 to last Monday date
if (orderDate.getDay()<3 || ((orderDate.getDay() === 3) && orderDate.getHours()<12)) {
lastMonday.setDate(lastMonday.getDate()+7);
} else {
// Otherwise. add 14 to last Monday date.
lastMonday.setDate(lastMonday.getDate()+14);
}
return lastMonday;
}
input:
let testDates = [
new Date(),
new Date(2021,7,18,11),
new Date(2021,7,18,13),
new Date(2021,9,1,11),
'bad date'
];
Output:
Wed Aug 18 2021 10:14:41 GMT+1200 (New Zealand Standard Time), Mon Aug 23 2021 10:14:41 GMT+1200 (New Zealand Standard Time)
Wed Aug 18 2021 11:00:00 GMT+1200 (New Zealand Standard Time), Mon Aug 23 2021 11:00:00 GMT+1200 (New Zealand Standard Time)
Wed Aug 18 2021 13:00:00 GMT+1200 (New Zealand Standard Time), Mon Aug 30 2021 13:00:00 GMT+1200 (New Zealand Standard Time)
Fri Oct 01 2021 11:00:00 GMT+1300 (New Zealand Daylight Time), Mon Oct 11 2021 11:00:00 GMT+1300 (New Zealand Daylight Time)
Invalid Date
Demo:https://jsfiddle.net/dzsf34ga/

How to convert a Date object to output only hh:mm am/pm

I am attempting to convert the following into a 12 hour am/pm format.
Currently I am recieving the Day, Month, Year and timezone.
Fixed by adding .toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.)/, "$1$3")*
<div id="time1"></div>
<div id="time2"></div>
var date = new Date('08/16/2019 12:00:00 PM UTC').toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3")
document.getElementById("time1").innerHTML = date;
var date = new Date('08/16/2019 6:00:00 am UTC').toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3")
document.getElementById("time2").innerHTML = date;
Basically what you have to do is use the Date() default javascript function and make sure you append the UTC timezone:
var date = new Date('08/16/2019 7:00:00 PM UTC')
date.toString=() //will then print out the timezone adjusted time
"Fri Aug 16 2019 22:00:00 GMT+0300 (Eastern European Summer Time)"
There are many built in javascript methods to handle converting date objects. This example will look to the browser to determine date format and time.
let time = Date.now();
time.toLocaleDateString();

getMonth getUTCMonth difference result

I found and inconsistent result when using the JavaScript date.getMonth() and date.getUTCMonth(), but only with some dates. The following example demonstrates the problem:
<!DOCTYPE html>
<html>
<body onload="myFunction()">
<p id="demo">Click the button to display the month</p>
<script type="text/javascript">
function myFunction()
{
var d = new Date(2012, 8, 1);
var x = document.getElementById("demo");
x.innerHTML=d;
x.innerHTML+='<br/>result: ' + d.getMonth();
x.innerHTML+='<br/>result UTC: ' + d.getUTCMonth();
}
</script>
</body>
</html>
The output of this example is:
Sat Sep 01 2012 00:00:00 GMT+0100 (Hora de Verão de GMT)
result: 8
result UTC: 7
If i change the date to (2012, 2, 1) the output is:
Thu Mar 01 2012 00:00:00 GMT+0000 (Hora padrão de GMT)
result: 2
result UTC: 2
In the first example, getMonth returns 7 and getUTCMonth returns 8. In the second example, both returns the same value 2.
Does anyone already experiences this situation? I am from Portugal and i think that it has something to be with my GMT but i don't understand why this is happening, because the examples are running in same circumstances.
Thanks in advances
You will see that, depending on YOUR TIMEZONE, the console logs may be different. I chose the first of the month '01' because it will be given a midnight default time '00:00:00', which will result in some timezones yielding February instead of March (you can get the full scoop here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse) :
let date1 = '2019-03-01'; // defaults to UTC
let date2 = '2019-03-01T14:48:00'; // LOCAL date/time
let dt1 = new Date(date1);
let dt2 = new Date(date2)
let month1 = dt1.getMonth();
let month2 = dt2.getMonth();
console.log("mon1: " + month1);
console.log("mon2: " + month2);
You will find that it is caused by DST difference.
Universal Time Zone date methods are used for working with UTC dates
Date returns month between 0 to 11
new Date(1976, 01 , 18) -
Wed Feb 18 1976 00:00:00 GMT+0530 (India Standard Time)
*getUTCDate return same as getDate() but returns Date based on World Time Zone, same with month and year
new Date(1976, 01 , 18).getUTCDate() -
17
new Date(1976, 01 , 18).getDate() -
18
new Date(1976, 02 , 18).getUTCMonth() -
2
new Date(1976, 01 , 18).getMonth() -
1
new Date(1976, 01 , 18).getYear() -
76
new Date(1976, 01 , 18).getUTCFullYear() -
1976
new Date(1976, 01 , 18).getFullYear() -
1976
A Date in js is just a timestamp, meaning there is no timezone information in any Date instance. A date is an absolute timed event (in opposition to a wall clock time which is relative to your timezone).
So… when you print the date to the console, because there is no timezone information in the date object, it will use your browser's timezone to format the date.
This is embarrassing because if you provide the same date to 2 clients, one in US and the other one in EU and ask them the date's month, because both are using their own timezone, you might end up with different answers.
To prevent this, getUTCMonth(); will use a default timezone of UTC (+0) instead of the client's browser so that the answer will be consistent whatever the client's timezone.

How to convert UTC datetime to different format

I have a datetime string in the following format.
var datetime="Thu May 5 05:30:00 UTC+0530 2011" ;
I want to convert it in the following format. How can I do it in javascript
"Thursday, 05 May 2011"
The globalize plugin has date parsing and formatting features.
Here is an example from the plugin page:
Globalize.format( new Date(1955,10,5), "dddd MMMM d, yyyy" ); // "Saturday November 5, 1955"
The date.js library is very useful for working with Dates.
Formatting examples:
Date.today().toString("dddd MMMM d, yyyy"); // Monday November 19, 2007
Date.today().toString(); // native .toString() functionality
Date.today().toString("M/d/yyyy"); // 11/19/2007
Date.today().toString("d-MMM-yyyy"); // 19-Nov-2007
new Date().toString("HH:mm"); // 18:45
Parsing examples:
Date.parse('today');
Date.parse('t + 5 d'); // today + 5 days
Date.parse('next thursday');
Date.parse('February 20th 1973');
Date.parse('Thu, 1 July 2004 22:30:00');

Categories

Resources