GetCoding
  • Home
  • Courses
  • Contact
Tag:

programming

BlogJavaScriptProgramming

How to Add Hours to a Date Object in JavaScript

by Matt Heff 1 year ago
written by Matt Heff 5 read

As if programming and dealing with dates did not have enough headaches that come from timezones, daylight savings, leap years the JavaScript Date API does not offer us a way to add hours to Date objects.

Fortunately with this tutorial we are going to do this ourselves and do it a couple of ways.

Method 1: Create a function ( use Date.setHours() )

function addHours(dateObj, hours){
   //We create a new Date Object so that we dont alter the one passed into the function (this is a pure function )
   const dateUpdated = new Date(dateObj.getTime());
   dateUpdated.setHours( dateUpdated.getHours() + hours);
   return dateUpdated;
}


const dateDemo = new Date('2022-06-22T12:00:00.000Z'); 
console.log(dateDemo); //2022-06-22T12:00:00.000Z

let dateModified = addHours(dateDemo,1)
console.log(dateModified); //2022-06-22T13:00:00.000Z

dateModified = addHours(dateDemo,3); //Original Date is not modified
console.log(dateModified); //2022-06-22T15:00:00.000Z

dateModified = addHours(dateModified,3)
console.log(dateModified); //2022-06-22T18:00:00.000Z


In the above function we create the variable dateUpdated and create a new Date Object so that the dateObj that is passed does not get modified. The Date.setHours() function updates the object, the above implementation is a pure state function, this will help prevent unexpected behaviours.

Method 2: Use NPM Package date-fns

If you are inclined to use NPM packages then this is a great one to make dates a little nicer in JavaScript or NodeJS

So this assumes you have NodeJS installed or an IDE where you can install NPM packages, you can install the package via the command below. We are only going to focus on demonstrating the addHours functionality.

npm install date-fns

import { addHours } from 'date-fns';

const date = new Date('2022-06-22T12:00:00.000Z');

//Add 1 hour to the existing date
let newDate = addHours(date, 1);
console.log(newDate); // 2022-06-22T13:00:00.000Z

//Add 2 hour to the already updated date
newDate = addHours(newDate, 2);
console.log(newDate); // 2022-06-22T15:00:00.000Z

//Original Date Object has not been modified
console.log(date); // 2022-05-15T12:00:00.000Z

The NPM package offers loads of date functions if you are in a situation to use this i would recommend it, anything that makes our lives easier with dates is worthwhile!

A few examples of date-fns functions

addDays, addHours, subHours, addMinutes, subMinutes, addSeconds, subSeconds, subDays, addWeeks, subWeeks, addYears, subYears,

Code Repo

Github: Example 1

Github: Example 2

1 year ago 0 comment
TwitterLinkedin
BlogJavaScriptProgrammingTutorial

Create your own JSON.stringify() function

by Matt Heff 1 year ago
written by Matt Heff

If you have been around the traps the JavaScript for a while you will know JSON.stringify(), you may have have even used it to compare objects, make clones of objects and arrays or even work with RESTful API’s. Using it is not enough of people like you and me, we must pull it apart, look under the hood and then make our own version of it.

This is a two way operation JSON.stringify() will turn objects into strings the inverse of that is JSON.parse() which will objectify strings. This is a good type of objectification.

Example of JSON.stringify() and JSON.parse()

const demoJsonObj = {
  mission: "CreateJsonStringify",
  timeToComplete: 10,
  useExistingFunction: false,
  reasons: ['Inquisitive','Masochist','Bragging Rights'],
  toolsAllowed:{
    language: "JavaScript",
    enhancer: "Coffee",
    motivation: "Binaural Beats",
    alternativeMethod: "Youtube - Check out my video tutorial"
  }
};

console.log(JSON.stringify(demoJsonObj));
// Output
//{"mission":"CreateJsonStringify","timeToComplete":10,"useExistingFunction":false,"reasons":["Inquisitive","Masochist","Bragging Rights"],"toolsAllowed":{"language":"JavaScript","enhancer":"Coffee","motivation":"Binaural Beats","alternativeMethod":"Youtube - Check out my video tutorial"}}


//Test the string is valid by parsing it back
console.log(JSON.parse(JSON.stringify(demoJsonObj)));

Ok that was nice and easy, we can pass the JavaScript Object and get a JSON String. Job done for 99% of folks out there. Not for us! Roll up your sleeves as we are only just about to GetCoding!

Where to begin?

Shall we jump in and start bashing out some code to start with? Or shall we have a think about what we are going to be doing here?

I’d start bashing on the keyboard, only to get 5 mins and and be like hmmmm. So here I am faced with the question how to we take a JSON Object and convert it into a JSON String?

What is a JSON Object? What can be in it? Do we need to cover all cases? Are there any weird things that could happen?

How do I go through each object item? What if it is an array of items? What if there is a object in the object? What if there is a array in the object or in the objects object array . . . . .does that even make sense?

Hmmm thats a lot of questions, Lets start with what is a JSON Object W3schools and MDN — I found the W3Schools page better it gave me a nice convenient list of what are valid JSON types

  • string
  • number
  • object
  • array
  • boolean
  • null

It also gave an example on how to loop through a JSON object. We are definitely going to need this!

//looping through the JSON Object using the object above
//variable is -- demoJsonObj -- just to remind you

for (const item in demoJsonObj) {
  console.log(item);
}

//This is handy, we can loop through the object and output each item. 

//Can you think how else we can use it?

This is excellent at least we have a starting point now, we know a bit about JSON and we definitely know that we need to handle these types. At some point we are going to need to check if the data we are looking at so lets make that code now.

Here your style preference can change how you write this, you could use if statements, switch or functions for each data type and return true/false.

function isStr(val){
    return typeof val === 'string';
}

function isNum(val){
 return typeof val === 'number';
}

// when checking a object we must ensure it is not null and not an array. Both null & Array has typeof object in JS
function isObj(val){
    return typeof val === 'object' && !Array.isArray(val) && val !== null;
};

// We need to check that it is an Array and also of type object

function isArray(val){
    return Array.isArray(val) && typeof val === 'object';
};

function isBool(val){
  return typeof val === 'boolean';
}

function isNull(val){
    return typeof val === 'string';
}

So that handles our Data types listed by W3Schools, there was a bit of knowledge I did have about type of for null and arrays returning as objects. If you didn’t have that you may get some weird results.

So now lets build out some code that will get a JSON Object and then loop through each item and check its type.

function CustomJsonStringify(obj){

 //check if it is string
  if(isStr(obj) ===true){
    return `"${obj}"`
  }
  if( isNum(obj) || isBool(obj)){
    return `${obj}`;
  }

  if(isArray(obj)){
    let arrayString = "";
    obj.forEach((val) => {
      arrayString += CustomJsonStringify;
      arrayString +=','
     });

    return `[${arrayString.replace(/,*$/, '')}]`;
  }




  // loop through each item in the object and handle it
  if(isObj(obj)){

        let objectString = ""; 
        let keys = Object.keys(obj);

    keys.forEach((key) => {
      let val = obj[key];
      objectString += `"${key}":${CustomJsonStringify(val)},`;

     });
     return `{${objectString.replace(/,*$/, '')}}`;

    }
  }


console.log(CustomJsonStringify(demoJsonObj));

//Pass string into JSON.parse() to check it is valid
console.log(JSON.parse(CustomJsonStringify(demoJsonObj)));

Conclusion

Here we have a basic stringify function , there are fringe cases which are not handled. and to make it more robust and a 1:1 equivalent we would need to add handling for

  • functions, undefined and Symbol values
  • Dates
  • NaN, Null and Infinity
  • Undefined

Hope this has been helpful to you, Ill have a youtube video going through this in the near future!

Code on GitHub

1 year ago 0 comment
TwitterLinkedin
BlogProgrammingTutorial

Introduction to JSON with Examples

by Matt Heff 1 year ago
written by Matt Heff

Over the last couple of years I have been marvelling that the pervasiveness and elegance of JSON, if you are working with data, API’s, server requests or database migrations then there is a good chance that you are going to come across a payload that contains this format. If you are lucky it will be this format!

What is JSON?

It stands for JavaScript Object Notation ( JSON ), It was derived from JavaScript (JS) as the name suggests and is a subset of JavaScript, it came about after object literals and array literals were added to the language. One of its great strengths is that it works across all programming languages. Because of this it is arguable the most populate way to store and transfer data across systems, API requests and migrating database data are two really populate uses.

When giving someone JSON data it should be in a FILE_NAME.json format, it generally is not a issue if it is a FILE_NAME.txt or other because it is plain text inside.

Syntax and Data Types

JSON data is stored as key/value pairs which is the same as Javascript Object properties, each item is separated by a comma, the object is sourraounded by {} curly brackets and arrays are sourrounded by [] the square brackets. The data itself has a Key/Name component which is sourrounded by “” double quotes followed by : (colon) and then the value (types are string ,number, null, boolean, array, object )

JSON Strings

Strings in JSON are contained by double quotes

{
    "firstName": "Matt",
    "lastName": "Heff"
}

JSON Null

Null values are empty values

{
    "dob": null
}

JSON Boolean

Boolean values are true or false in JSON

{
    "education" : false
}

JSON Numbers

A number must either be an integer ( eg 10 ) or a floating-point ( eg 10.1 )

{
    "age" : 15
}

JSON Object

JSON Objects elements which are wrapped in curly brackets, inside a object we can have any number of key/value pairs, each is separated by a comma.

{
    "firstName": "Matt",
    "lastName": "Heff",
    "dob": null,
    "education" : false
}

JSON Arrays – Multiple Records

JSON arrays are wrapped with the square brackets. Inside an array we can have as many objects as we like, each needs to be separated by a comma.

[
  {
    "firstName": "Matt",
    "lastName": "Heff",
    "dob": null,
    "education": false,
    "age": 15

  },{
    "firstName": "John",
    "lastName": "Smith",
    "dob": "12/12/2000",
    "education": true,
    "age": 21
  }
]

Multiple Records in an Array with Nested Array

[
  {
    "firstName": "Matt",
    "lastName": "Heff",
    "dob": null,
    "education": false,
    "languages": ["JSON","Solidity","JavaScript","Node.js"],
    "age": 15
  },
  {
    "firstName": "John",
    "lastName": "Smith",
    "dob": "12/12/2000",
    "education": true,
    "languages": null,
    "age": 21,
    "educationItems": 
         [
           {"schoolLevel":"High School","yearGraduated":2020},
           {"schoolLevel":"University","yearGraduated":null},
        ]
  }    
]

Wrangling JSON Data in JavaScript

JSON is based on a subset of the JavaScript language, so it works really nicely with JS. We are able to convert JSON data into JavaScript objects pretty simply and with tools built in.

There is a JSON object in JavaScript that offers us two methods where we can encode/decode JSON data. parse() and stringify()

When we recieve a JSON data payload from a server/api request it is not going to be a Javascript Object by default, it is going to be a string so we will need to convert it into a JavaScript Object like below:

// from our JSON example above we make a sample string
const jsonDataExampleString = `{    "firstName": "Matt",    "lastName": "Heff",    "dob": null,    "education": false,    "age": 15 }`;

// lets convert it into a JavaScript Object!
const record = JSON.parse(jsonDataExampleString);

console.log(record.firstName); Matt
console.log(record.lastName); // Heff
console.log(record.dob); //null
console.log(record.education); //false
console.log(record.age); // 15

When we need to send some JSON over a request or two write it into a file we need to convert it to a string, JSON.stringify() does this for us:

// Make a JavaScript Object that is correct JSON
const record = { 
    "firstName" : "Matt",
    "lastName" : "Heff",
    "dob" : null,
    "education": false,
    "age": 15
}

// convert the object into a string
const jsonDataExampleString  = JSON.stringify(record );


console.log(jsonDataExampleString);

//{    "firstName": "Matt",    "lastName": "Heff",    "dob": null,    "education": false,    "age": 15 }

JSON Resources

  • Introducing JSON — Learn about JSON language supported features.
  • JSONLint — A JSON validator to verify if the JSON string is valid.
  • JSON.dev — A little tool for viewing, parsing, validating, minifying, and formatting JSON.
  • JSON Schema — Annotate and validate JSON documents according to your own specific format.
1 year ago 0 comment
TwitterLinkedin

Recent Posts

  • How to read environment variables with Node.js
  • AI – What is Natural Language Processing (NLP)
  • Web3 RPC Nodes
  • Drupal 9 – Custom module development – Simple Module
  • Create a RESTful API in NodeJS

About

About

GetCoding is a blog and tech educational resource specialized in programming, Web3, blockchain and everything in between. Follow us to help you understand and GetCoding!

Stay Connect

Twitter Linkedin Youtube Email

Popular Posts

  • 1

    Writing your first Ethereum Smart Contract

    1 year ago
  • 2

    Create your own JSON.stringify() function

    1 year ago
  • 3

    Install Metamask and get Testnet Tokens

    1 year ago
  • 4

    Introduction to JSON with Examples

    1 year ago
  • 5

    What is an AMM ( Automated Market Maker)

    1 year ago

Categories

  • Blockchain (4)
  • Blog (7)
  • Featured (3)
  • Learning (1)
  • Programming (5)
    • JavaScript (3)
    • NodeJS (1)
    • PHP (1)
  • Technologies (2)
    • Drupal (1)
  • Thought Provoking (1)
  • Tutorial (6)
  • Uncategorized (3)

Recent Posts

  • How to read environment variables with Node.js

    6 months ago
  • AI – What is Natural Language Processing (NLP)

    10 months ago
  • Web3 RPC Nodes

    1 year ago

Featured Posts

  • How to read environment variables with Node.js

    6 months ago
  • AI – What is Natural Language Processing (NLP)

    10 months ago
  • Web3 RPC Nodes

    1 year ago

Subscribe Newsletter

Subscribe my Newsletter for new blog posts, tips & new photos. Let's stay updated!

  • Twitter
  • Linkedin
  • Youtube
  • Email
GetCoding
  • Home
  • Courses
  • Contact